Skip to content

Instantly share code, notes, and snippets.

@raecoo
Last active April 25, 2024 13:19
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save raecoo/dcbac9e94198dfd0801be8a0cbb14570 to your computer and use it in GitHub Desktop.
Save raecoo/dcbac9e94198dfd0801be8a0cbb14570 to your computer and use it in GitHub Desktop.
Save JSON object to file in Chrome Devtool
// e.g. console.save({hello: 'world'})
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
@imhuwq
Copy link

imhuwq commented Mar 12, 2020

This is awesome!

@kaliavarun
Copy link

This is really awesome. initMouseEvent is deprecated. You can replace it like this.

(function (console) {
    console.save = function (data, filename) {
        if (!data) {
            console.error('Console.save: No data')
            return;
        }
        if (!filename) filename = 'console.json'
        if (typeof data === "object") {
            data = JSON.stringify(data, undefined, 4)
        }
        var blob = new Blob([data], { type: 'text/json' }),
            a = document.createElement('a')
        var e = new MouseEvent('click', {
            view: window,
            bubbles: true,
            cancelable: false
        });

        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
        a.dispatchEvent(e)
    }
})(console)

@yor-so
Copy link

yor-so commented Jan 23, 2024

You can skip the mouse event. The click() event works

console.save = function (data, filename) {
  if (!data) {
    console.error('Console.save: No data');
    return;
  }
  
  if (!filename) {
    filename = 'console.json'; 
  }
  
  if (typeof data === "object") {
    data = JSON.stringify(data, undefined, 4);
  }
  
  var blob = new Blob([data], { type: 'text/json' });
  var a = document.createElement('a');

  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
  a.click();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment