javascript 每个页面加载只运行一次 Greasemonkey 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4190442/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:38:51  来源:igfitidea点击:

Run a Greasemonkey script only once per page load?

javascriptgreasemonkeytampermonkey

提问by Joren

If you create a Greasemonkey script with @include *and go to a site like youtube, it runs the script 20+ times every time you refresh. This is on Firefox, not sure about Chrome.
Is there a way to prevent this?

如果您使用 Greasemonkey 脚本创建@include *并访问 youtube 等网站,则每次刷新时它都会运行该脚本 20 多次。这是在 Firefox 上,不确定 Chrome。
有没有办法防止这种情况?

回答by Brock Adams

First, you probably don't want the script to run in iFrames.
You can block that using the @noframesdirectivewhich now works in both Greasemonkey and Tampermonkey as of October, 2014.

首先,您可能不希望脚本在 iFrame 中运行。
您可以使用@noframes2014 年 10 月起在 Greasemonkey 和 Tampermonkey 中都有效指令来阻止它。

For older versions, or for script engines that don't support @noframes, you can use this code, just after the metadata block:

对于旧版本或不支持的脚本引擎@noframes,您可以在元数据块之后使用此代码:

if (window.top != window.self)  //don't run on frames or iframes
{
    //Optional: GM_log ('In frame');
    return;
}


Second, you can wait and fire your GM code, once, on page load. Wrap everything in a main()and call it on the loadevent, like so:


其次,您可以在页面加载时等待并触发您的 GM 代码一次。将所有内容包裹在 a 中main()并在load事件中调用它,如下所示:

window.addEventListener ("load", LocalMain, false);

function LocalMain () {
    // Your code goes here.
}



Third, you can exclude sites or pages by adding // @excludedirectives to the metadata block.

第三,您可以通过向// @exclude元数据块添加指令来排除站点或页面。

Overall, it's best to avoid universally included GM scripts, if possible.

总的来说,如果可能的话,最好避免普遍包含的 GM 脚本。

Other methods might set flags or reload the page with URL parameters. These get tricky so save them as a last resort.

其他方法可能会设置标志或使用 URL 参数重新加载页面。这些变得棘手,因此将它们保存为最后的手段。

回答by Dr.Molle

You can for example store the given location in a persistent variable. On page load you have to check, if the current location is already stored in this variable.

例如,您可以将给定的位置存储在一个持久变量中。在页面加载时,您必须检查当前位置是否已存储在此变量中。

If not, you set the variable and run your function, if yes do nothing.

如果没有,您设置变量并运行您的函数,如果是,则什么都不做。

How to store persistent variables: GM_setValue

如何存储持久变量:GM_setValue