开发者

Greasemonkey & global variables

开发者 https://www.devze.com 2023-01-08 09:58 出处:网络
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

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 pa开发者_如何学Pythonge the condition's value is always true.

Is there a way to use global variables with Greasemonkey?


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


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.


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


If you're trying to maintain a variable through multiple page refreshes, you will need to store it in a cookie.

However if you simply want a global variable within the scope of a single page:

var imGlobal;
(function(){ // Greasemonkey crap...
...
imGlobal = "Totally";
})();
alert(imGlobal) // Alerts "Totally"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号