Greasemonkey & global variables

22,559

Solution 1

You have to use unsafeWindow in order to create a global variable that is available to the page's javascript scope.

if (unsafeWindow.myVar == undefined) {
   unsafeWindow.myVar = "myVar";
}

But you can't expect this variable to exist when you refresh the page, because normal javascript does not work that way. If you want to save some data across page loads then I suggest that you use GM_setValue & GM_getValue

Solution 2

You are using a global variable, but global variables only last as long as the page does so when you refresh you are clearing all global variables. The only way to save data past a page refresh is with a cookie, upload to the a server, or the HTML5 storage API. With greasemonkey probably you would want to use a cookie.

Solution 3

To set global variables in GreaseMonkey, use @grant none, otherwise it uses unsafeWindow, which is only available to GreaseMonkey. There are some security concerns. See http://wiki.greasespot.net/@grant

Share:
22,559
gombost
Author by

gombost

Updated on July 09, 2022

Comments

  • gombost
    gombost almost 2 years

    I'm noob with JavaScript and Greasemonkey and I'd like to write a simple script.

    I know that Greasemonkey wraps your code with an anonymous function so your variables won't exist after leaving the current page. However, I need a global variable. I tried to use the unsafeWindow and window objects something like this:

    if (window.myVar == undefined) {
       window.myVar = "myVar";
    }
    

    If I refresh the page the condition's value is always true.

    Is there a way to use global variables with Greasemonkey?

  • Anderson Green
    Anderson Green over 11 years
    Is there a way to save variables besides strings, booleans, and numbers across multiple pages (like GM_setValue and GM_getValue)? I saw a script for Greasemonkey that could do this once, but I don't remember which one it was.
  • Orvid King
    Orvid King over 10 years
    De-serialize the object to JSON, then serialize it when you load the variable.
  • Rudey
    Rudey about 5 years
    That documentation page you have linked slightly contradicts what you're saying. @grant none is the default, you must specify unsafeWindow if you want it.