Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greasemonkey & global variables

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?

like image 223
gombost Avatar asked Jul 23 '10 20:07

gombost


People also ask

What is Greasemonkey used for?

Allows you to customize the way a web page displays or behaves, by using small bits of JavaScript. You can write your own scripts, too. Check out http://wiki.greasespot.net/ to get started. Many scripts already exist, probably ones to enhance your favorite sites.

Is Tampermonkey or Greasemonkey better?

Tampermonkey is more recent than Greasemonkey and supports all the major browsers. Furthermore, Tampermonkey is fairly easy to use for both beginners and advanced users. It's easier to install scripts on Greasemonkey but Tampermonkey's features like code checking help you be more accurate.

Can Tampermonkey scripts steal passwords?

Yes, userscripts can steal your passwords. That's the bottom line.


1 Answers

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

like image 52
erikvold Avatar answered Sep 23 '22 01:09

erikvold