每页加载只运行一次Greasemonkey脚本? [英] Run a Greasemonkey script only once per page load?

查看:111
本文介绍了每页加载只运行一次Greasemonkey脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您使用 @include * 创建Greasemonkey脚本并转到类似youtube的网站,则每次刷新时它都会运行脚本20次以上。这是在Firefox上,不确定Chrome。

有没有办法防止这种情况?

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?

推荐答案

首先,您可能不希望脚本在iFrame中运行。

您可以使用 @noframes 指令,自2014年10月起,现在可用于Greasemonkey和Tampermonkey。

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

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

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

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



其次,你可以等待并解雇你的GM代码,一次,在页面加载。将所有内容包装在 main()中并在 load 事件中调用它,如下所示:


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

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

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


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

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

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

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

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

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

这篇关于每页加载只运行一次Greasemonkey脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆