Home > Software design >  Save a JS array to file on every reload in chrome or firefox?
Save a JS array to file on every reload in chrome or firefox?

Time:03-09

I have a JS array whose value changes every time I reload the browser. I want to log the array data (in a file or append to a temp variable that stays even after reload) every time I reload the page.

I tried this script but it has to be manually executed after each reload. Any idea, how can I achieve this?

CodePudding user response:

Thanks to @Sebastian's comment and this script, I was able to create a user script and achieve exactly what I wanted.

Here is the user script I created.

// ==UserScript==
// @name         MyScript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        <url>
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// ==/UserScript==

(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)

// Create an incremental file name
var lastIndex = sessionStorage.getItem('arr')
sessionStorage.setItem('arr',   lastIndex)
var fileName = 'dataset-'   lastIndex   '.json'

// Save the file
console.save(array, fileName)
console.log(fileName   ' saved.')

Then I also disabled the "Ask every time to save download" option in Firefox so that the file is saved without a prompt.

  • Related