user6468132 user6468132 - 1 year ago 110
Javascript Question

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;

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

What should I do?

Answer Source

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*
// @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
    document.title = saved.title;

Usage in console:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download