Last active
August 9, 2020 12:46
-
-
Save nathansmith/4ff5887ecd9f452b3a92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = (function(window) { | |
'use strict'; | |
var console = window.console; | |
var document = window.document; | |
// For comparison. | |
var f = 'function'; | |
var o = 'object'; | |
// Exit, if no window.console | |
if (typeof console !== o) { | |
return; | |
} | |
/* | |
Check to ensure we're not overwriting | |
a future, native console.save method. | |
Also, ensure all of the featuers are | |
available to actually create a file. | |
*/ | |
var bool = | |
typeof console.save !== f && | |
typeof Blob === f && | |
typeof window.URL === f && | |
typeof document.createEvent === f; | |
// If unsupported, make it a no-op. | |
if (!bool) { | |
console.save = function(){}; | |
// Exit. | |
return; | |
} | |
// Create the function. | |
console.save = function(data, filename) { | |
if (!data) { | |
console.error('console.save: NO DATA'); | |
return; | |
} | |
if (!filename) { | |
filename = 'console.json'; | |
} | |
if (typeof data === o) { | |
data = JSON.stringify(data, undefined, 2); | |
} | |
var type = 'text/json'; | |
var blob = new Blob([data], {type:type}); | |
var e = document.createEvent('MouseEvents'); | |
var a = document.createElement('a'); | |
e.initMouseEvent( | |
'click', | |
true, | |
false, | |
window, | |
0, | |
0, | |
0, | |
0, | |
0, | |
false, | |
false, | |
false, | |
false, | |
0, | |
null | |
); | |
a.download = filename; | |
a.href = window.URL.createObjectURL(blob); | |
a.dataset.downloadurl = [type, a.download, a.href].join(':'); | |
a.dispatchEvent(e); | |
// END: function. | |
}; | |
// END: closure. | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment