execute function only once

后端 未结 1 1715
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 15:53

I\'m writing a greasemonkey script and want to call the start function only once after the page loads - it\'s for facebook. First I started with following code:

相关标签:
1条回答
  • 2020-12-21 16:35

    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;
      
    0 讨论(0)
提交回复
热议问题