Search code examples
javascripthtmltampermonkey

Issues creating a global variable list in javascript (Tampermonkey)


I'd like to create a global variable list in javascript that will add new elements to the list. I need it global because I'm using Tampermonkey, and I want to keep old elements inside the list and able to add new elements to it.

How can I do this correctly?

I have tried something like this but it's not working :c

var check_empty = GM_getValue("arr_names");
if(Array.isArray(check_empty) && check_empty.length > 0){ // list of usernames exists and is not empty
    var user = "RandomUsername";
    GM_setValue("arr_names", check_empty.push(user));
    var arr = GM_getValue("arr_names");
    for(var i=0; i<arr.length; i++){
        window.alert("Length: " + arr.length + " Elements inside: " + arr[i]);
    }
}
else{ // create the list
    GM_setValue("arr_names",["Initialized"]);
}

So let's say I run this code 3 times. Then the list needs to look like this:

["Initialized", "RandomUsername", "RandomUsername"]

If 4 times excuted, then like this:

["Initialized", "RandomUsername", "RandomUsername", "RandomUsername"]

Solution

  • GM_setValue("arr_names", check_empty.push(user));
    

    As mentioned in the comments, check_empty.push(user) returns the length of the updated array, but you should pass the array here.

    You can push the element in the previous line and use the mutated array:

    check_empty.push(user);
    GM_setValue('arr_names', check_empty);