javascript Greasemonkey 和全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3321978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Greasemonkey & global variables
提问by gombost
I'm noob with JavaScript and Greasemonkey and I'd like to write a simple script.
我是 JavaScript 和 Greasemonkey 的菜鸟,我想写一个简单的脚本。
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:
我知道 Greasemonkey 使用匿名函数包装您的代码,因此您的变量在离开当前页面后将不存在。但是,我需要一个全局变量。我尝试使用 unsafeWindow 和 window 对象,如下所示:
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?
有没有办法在 Greasemonkey 中使用全局变量?
回答by erikvold
You have to use unsafeWindowin order to create a global variable that is available to the page's javascript scope.
您必须使用unsafeWindow来创建一个可用于页面 javascript 范围的全局变量。
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
但是当你刷新页面时,你不能指望这个变量存在,因为普通的 javascript 不会那样工作。如果你想在页面加载中保存一些数据,那么我建议你使用GM_setValue& GM_getValue
回答by qw3n
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.
您正在使用全局变量,但全局变量仅在刷新时清除所有全局变量时页面持续存在。在页面刷新后保存数据的唯一方法是使用 cookie、上传到服务器或 HTML5 存储 API。对于greasemonkey,您可能想要使用cookie。
回答by Chad Hedgcock
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
要在 GreaseMonkey 中设置全局变量,请使用@grant none,否则使用unsafeWindow,仅适用于 GreaseMonkey。有一些安全问题。见http://wiki.greasespot.net/@grant
回答by Chase Wilson
If you're trying to maintain a variable through multiple page refreshes, you will need to store it in a cookie.
如果您尝试通过多次页面刷新来维护变量,则需要将其存储在 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"

![javascript jQuery 等效于 document.forms[0].elements[i].value; 是什么?](/res/img/loading.gif)