console.save

A simple way to save objects as .json files or to save blobs as files from the console.

  1. // ==UserScript==
  2. // @name console.save
  3. // @namespace http://bgrins.github.io/
  4. // @version 0.2.0
  5. // @description A simple way to save objects as .json files or to save blobs as files from the console.
  6. // @author Devtools Snippets
  7. // @match http://*/*
  8. // @match https://*/*
  9. // @grant none
  10. // ==/UserScript==
  11.  
  12. (function () {
  13. 'use strict';
  14.  
  15. window.console.save = function (data, filename) {
  16.  
  17. if (!data) {
  18. console.error('Console.save: No data')
  19. return;
  20. }
  21.  
  22. if (!filename) {
  23. console.error('Console.save: No filename')
  24. return
  25. }
  26.  
  27. var blob
  28. if (Object.prototype.toString.call(data) === '[object Blob]') {
  29. blob = data
  30. } else {
  31. if (typeof data === "object") {
  32. data = JSON.stringify(data, undefined, 4)
  33. }
  34. blob = new Blob([data], { type: 'text/json' })
  35. }
  36.  
  37. var e = document.createEvent('MouseEvents')
  38. var a = document.createElement('a')
  39.  
  40. a.download = filename
  41. a.href = window.URL.createObjectURL(blob)
  42. a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
  43. e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
  44. a.dispatchEvent(e)
  45. }
  46. })();