Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

javascript - execute function only once

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...