0

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?

bluelurker
  • 1,353
  • 3
  • 19
  • 27
  • 1
    See [Persist variables between page loads](/q/29986657/4642212) and try a userscript. – Sebastian Simon Mar 05 '22 at 19:34
  • 1
    This doesn't seem clear to me. Are you the owner of the page or the client? What's the page/array and expected result? This may also be an [xy problem](https://meta.stackexchange.com/a/233676/399876) without seeing more context. – ggorlen Mar 05 '22 at 19:48
  • @ggorlen I don't own the website. It's a client website and we don't maintain it. I know exactly what I want to do. – bluelurker Mar 05 '22 at 20:24

1 Answers1

0

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.

bluelurker
  • 1,353
  • 3
  • 19
  • 27