Search code examples
javascriptarrayslocal-storageuserscripts

Preserve variables set within userscript


I am writing a script in tampermonkey.

I have an var arr = ["alex", "felix"] which can be updated according to the usage of script. When there is a change I added the value to the arr as; arr.push("kelix")

But when the script is reloaded, the arr is still var arr = ["alex", "felix"]. The newValue is not pushed to the array. So how can I preserve the changes in the variable arr?

What should I do?


Solution

  • I would use localStorage. Below see example script that will allow you to change document title and will remember it over reloading:

    // ==UserScript==
    // @name        Remember value
    // @namespace   util
    // @description Test that remembers any saved value after reload
    // @include     http://stackoverflow.com/*
    // @version     1
    // @grant       none
    // ==/UserScript==
    // Try to load saved data from local storage
    const FIELD_NAME = "userscript_TEST";
    var saved = localStorage[FIELD_NAME]?JSON.parse(localStorage[FIELD_NAME]):{};
    
    // Save data when leaving tab
    window.addEventListener("unload", function() {
        localStorage[FIELD_NAME] = JSON.stringify(saved);
    });
    // This changed document title and remembers it
    window.changeDocumentTitleForever = function(title) {
        saved["title"] = title;
        document.title = title;
    }
    
    // This loads title after loading page
    if(saved.title)
        document.title = saved.title;
    

    Usage in console:

    changeDocumentTitleForever("test")