Maintain the values of variables established in a userscript

Currently, I am working on a Tampermonkey script and facing an issue.

In my script, I declared an array as var arr = ["alex", "felix"] which can be updated dynamically based on the script's usage. Each time there is a change, I update the value by adding it to the array like this: arr.push("kelix")

The problem arises when the script is reloaded, and the array reverts back to its initial state var arr = ["alex", "felix"]. The new value added is not preserved in the array. So, how can I ensure that changes made to the variable arr are saved even after reloading the script?

Could anyone provide guidance on how to tackle this issue effectively?

Answer №1

If you're looking to persist data even after reloading a page, one way to achieve this is by using the localStorage feature in JavaScript. Here is an example script that demonstrates how you can change the document title and have it remembered across reloads:

// ==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 changes document title and remembers it
window.changeDocumentTitleForever = function(title) {
    saved["title"] = title;
    document.title = title;
}

// This loads the title after the page has loaded
if(saved.title)
    document.title = saved.title;

To use this in the console, simply call the function with the desired title like so:

changeDocumentTitleForever("test")

Answer №2

When creating a userscript, it is advisable to use GM_setValue and GM_getValue over localStorage.

var list = ["john", "sarah"];
try { list = JSON.parse(GM_getValue('list', '["john", "sarah"]')); }
catch (_ignore) { /* continue even if JSON.parse fails */ }
// manipulate the list
list.push('emily');
GM_setValue('list', JSON.stringify(list));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...

jQuery draggable elements can be easily dropped onto droppable areas and sorted

I need help with arranging the words in the bottom tiles by sorting them from "Most Like Me" to "Least Like Me" droppable areas. Currently, I am able to drag and drop the words into different boxes, but it ends up stacking two draggable items on top of eac ...

Using v-model in Vue with jQuery integration

I wrote a jQuery code that is executed when the mounted hook runs mounted() { this.$progress.finish(); var geocoder = new google.maps.Geocoder(); var marker = null; var map = null; function initialize() { var $latitude = document.getEl ...

Mapping custom colors to paths in D3 Sunburst visualizations can add a vibrant and unique touch

Currently, I am in the process of developing a D3 Sunburst Vue component and utilizing the npm package vue-d3-sunburst for this purpose. To access the documentation for the package, please visit: https://www.npmjs.com/package/vue-d3-sunburst The document ...

ReactJS - ref returns a value of "undefined"

I'm currently working on a project using ReactJS alongside NextJS. I've encountered an issue where my console is showing 'undefined' when I try to set a ref. This is quite puzzling to me, and I'm struggling to find a solution to th ...

AJAX code fetching dynamic content without relying on file loading

When I load my program, the dynamic code does not appear on the page until I reload it again. I attempted to use the onload event in the body to load content from an XML file using AJAX, but it only works after closing and reopening the program, not dynam ...

There are several ways to input values from JavaScript into ASP controls

Greetings, I am a newcomer to the world of web development, specifically using ASP.NET. I have been struggling with the task of passing or returning a value to display on an HTML element, such as an input field. Despite trying multiple solutions that I fo ...

The id property of undefined cannot be accessed in the discord.js library

I am currently developing a Discord bot that assigns a role temporarily whenever a specific word is mentioned. Despite thoroughly checking my code, I continue to encounter the following error: message.member.roles.add(role555.id); ...

Is there a way to incorporate the image that was uploaded from the server onto an HTML page without using the file extension?

$('#userInfoPhoto').html(function () { return '<img src="../uploads/' + thisUserObject.profileimage + '" alt = "userphoto" style="width:250px; height:250px"/>' }); This script is essential for rendering images on th ...

Whenever I attempt to populate my modal box with data from my selection, I am greeted with an error message stating "invalid object passed in." What could be causing this issue?

Whenever I click on a customer from my table to display their details in a modal box, I keep getting an error message that says "invalid object passed in." The method client is responsible for populating the data and displaying it through a partial view. T ...

Using JavaScript to dynamically load Cascading Style Sheets based on the current

I am trying to dynamically load different CSS files based on the current date (season). I attempted to tweak an image script that I found on Stack Overflow, but it didn't yield the desired result. Could someone please guide me on where I might be ma ...

No data was returned in the responseText of the XMLHttpRequest

I am facing an issue where my XMLHttpRequest code is executing without any errors, but it always returns an empty responseText. Here is the JavaScript code that I am using: var apiUrl = "http://api.xxx.com/rates/csv/rates.txt"; var request = new XMLH ...

Updates are not being reflected in LocalStorage

This section features the card.js code snippet: import React, { useState, useEffect } from 'react' // import { PdtList } from './Cart'; export default function Card(props) { let list = JSON.parse(localStorage.getItem("context&q ...

Creating a central navigation menu for a website

Currently, I am working on incorporating a menu in the center of a webpage (please note that this is not a top navigation menu). Here is the initial setup: https://i.sstatic.net/3arql.png Users are able to click on various menu items to access different ...

The .change() function is only executing once and not triggered by multiple clicks

I have a JavaScript file that runs automatically through an HTML script. The issue I am facing is with the putToggleCall() function, which should be triggered every time one of the toggles is clicked. However, it only executes once, even before the docum ...

Iterating recursively through a tree structure to update properties using Mongoose

I have a unique structure resembling a tree that I've set up to store comments. Each "comment" acts as a node with a "parent" property linking it to another "comment" node. Additionally, I've included a "replyCount" field on each node to keep tra ...

ng-repeat unable to function within a textarea

Could you help me troubleshoot why the ng-repeat is not functioning properly within a textarea? Oddly enough, it works fine when moved outside of the textarea. <textarea> <style ng-repeat="entry in bgTakeoverSettings.breakPoints"> ...

Ways to determine the completion of the compilation process in Angular using the $compile service

Imagine having a popup directive that inherits a string template for the content it should display from the $scope. scope: { template: '=popInfo'//<div another directive></div> } This template string may even include another dire ...

Updating input value using v-model in Vue.js does not reflect changes

I'm struggling with formatting numbers that I input in an HTML text box. I have a function that is supposed to format the number when I click out of the input box, but the updated value is not reflected in the v-model. The function is working correct ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...