execute function only once

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 16:22:38

The issue is that your whole Greasemonkey script is executing more than once. Greasemonkey will run on iframes, just as though they were the main page -- if the iframe matches the @include, @exclude, and @match directives of your script.

There is no point in trying to track state like that, the function will only run once per script execution, unless you deliberately call it more than once (Which is not shown in the question). And scripts can't normally share information between execution instances (nor is that needed here).

Also, there is no need to use jQuery(document).ready() because, unless you are injecting the script into the target page, Greasemonkey fires at document.ready by default.

To solve the multiple run issue:

  1. Tune your @include, @exclude, and @match directives to eliminate as many undesired iframes as you reasonably can.
  2. Add code like this near the top of your script:

    if (window.top != window.self)  //-- Don't run on frames or iframes.
        return;
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!