油猴与全局变量
我是 JavaScript 和 Greasemonkey 新手,我想编写一个简单的脚本。
我知道 Greasemonkey 使用匿名函数包装您的代码,因此您的变量在离开当前页面后将不存在。但是,我需要一个全局变量。 我尝试使用 unsafeWindow 和 window 对象,如下所示:
if (window.myVar == undefined) {
window.myVar = "myVar";
}
如果我刷新页面,则条件的值始终为 true。
有没有办法在 Greasemonkey 中使用全局变量?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须使用 unsafeWindow 才能创建可用于页面 JavaScript 范围的全局变量。
但是你不能指望刷新页面时这个变量会存在,因为普通的 javascript 不会那样工作。如果您想在页面加载时保存一些数据,那么我建议您使用 GM_setValue & GM_getValue
You have to use unsafeWindow in order to create a global variable that is available to the page's javascript scope.
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
您正在使用全局变量,但全局变量仅在页面存在时持续存在,因此当您刷新时,您将清除所有全局变量。在页面刷新后保存数据的唯一方法是使用 cookie、上传到服务器或 HTML5 存储 API。对于greasemonkey,您可能会想要使用cookie。
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.
要在GreaseMonkey中设置全局变量,请使用
@grant none
,否则使用unsafeWindow
,该功能仅适用于GreaseMonkey。存在一些安全问题。请参阅http://wiki.greasespot.net/@grantTo set global variables in GreaseMonkey, use
@grant none
, otherwise it usesunsafeWindow
, which is only available to GreaseMonkey. There are some security concerns. See http://wiki.greasespot.net/@grant如果您尝试通过多次页面刷新来维护变量,则需要将其存储在 cookie 中。
但是,如果您只想在单个页面范围内使用全局变量:
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: