execute function only once

你。 提交于 2019-11-28 10:40:45

问题


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:

function start(){
    alert("hello");
}

start();

The start() function was executed more then once. So I changed the code to following:

jQuery.noConflict();
window.stoop = 0;
jQuery(document).ready(function(){
    if(window.stoop == 0){
        start();
    }
    window.stoop = 55;
    //or window.stoop++;
});


function start(){
    alert("hello");
}

The problem is that the window.stoop value won't change.

I tried with

var stoop = 0;
stoop++;

and

var obj = {};
obj.stoop = 0;
obj.stoop++;

too, but these ways didn't work neither.

What am I doing wrong? I'm in Europe right now -it's night, so I will answer your questions later.


回答1:


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;
    


来源:https://stackoverflow.com/questions/12117902/execute-function-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!