Skip to content

Instantly share code, notes, and snippets.

@KMurphs
Last active February 16, 2023 16:00
Show Gist options
  • Save KMurphs/64279307753a085049bdf2960837d87b to your computer and use it in GitHub Desktop.
Save KMurphs/64279307753a085049bdf2960837d87b to your computer and use it in GitHub Desktop.
Save JS Object as file from DevTools
/**
* Given some Javascript object, the function will have the browser download it as a
* json file (exactly like if it was downloaded from some server).
* The content of the file downloaded by the browser would be the "data" object input.
* One could also pass a name for the file to be downloaded to the function.
* References:
* - https://www.freecodecamp.org/news/how-to-use-the-browser-console-to-scrape-and-save-data-in-a-file-with-javascript-b40f4ded87ef/
* - https://github.com/edubey/browser-console-crawl/blob/master/single-story.js
* @date 2021-06-18
* @param {object} data
* @param {string} filename
* @returns {void}
*/
function saveDataAsFile(data, filename = "browser-scrapped.json") {
if (!data) { console.error('Console.save: No data'); return; }
// Convert data into a pretty json string
if (typeof data === "object") { data = JSON.stringify(data, undefined, 4); }
// Create dummy file(blob), link and event to simulate download
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
// Setup the dummy a link
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
// Setup the dummy event
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
// Simulate a click on the link. The browser will then start a download of our fictious file
a.dispatchEvent(e);
}
// Example: Extracts some data from page and save it as a file on the hard drive
function scrappePage() {
const currentURL = window.location.href;
const dataToSave = { url: currentURL };
dataToSave.links = Array.from(document.querySelectorAll(".mfr-part-num a")).map(item => item.href);
return dataToSave;
}
var scrappePageAndDownload = () => saveDataAsFile(scrappePage());
scrappePageAndDownload();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment