2011-01-10 124 views
2

我知道您可以使用return;从Greasemonkey脚本返回,但前提是您不在其他函数中。例如,这是不行的:有没有办法退出Greasemonkey脚本?

// Begin greasemonkey script 
function a(){ 
    return; // Only returns from the function, not the script 
} 
// End greasemonkey script 

有一个内置在Greasemonkey的功能,让我停止执行脚本,在脚本的任何地方?

谢谢

回答

3

呀,你也许可以这样做:

(function loop(){ 
    setTimeout(function(){ 
     if(parameter === "abort") { 
      throw new Error("Stopped JavaScript."); 
     } 
     loop(); 
    }, 1000); 
})(parameter); 

只需通过设置变量参数的值中止中止脚本,这可以是一个常规的变量或Greasemonkey变量。如果它是一个Greasemonkey变量,那么可以使用Firefox中的about:config直接通过浏览器修改它。

+0

我在想抛出一个错误。但是,这会干扰页面上的其他脚本吗? – 2011-01-10 21:46:45

+1

@SimpleCoder,我的其他Greasemonkey脚本,对于同一页面,本地脚本工作正常。 – Anders 2011-01-10 21:54:44

4

是否有内置的Greasemonkey功能,可以让我在脚本的任何位置停止执行脚本?

These are the current Greasemonkey functions


你可以抛出一个异常,就像Anders的回答一样,但除非在特殊情况下,我宁愿不要例外。

总有老的经典,do-while ...

// Begin greasemonkey script 
var ItsHarikariTime = false; 

do { 
    function a(){ 
     ItsHarikariTime = true; 
     return; // Only returns from the function, not the script 
    } 
    if (ItsHarikariTime) break; 

} while (0) 
// End greasemonkey script 


或者,你可以使用函数返回,而不是本地的全局。

1

如果你在函数的嵌套调用中,throw看起来像是唯一的解决方案,一起退出脚本。但是,如果您想要在脚本内的某处(不在函数调用中)退出脚本,则建议将所有脚本包装为匿名函数。

// begin greasemonkey script 

(function(){ 


// all contents of the script, can include function defs and calls 
... 
... 
if <...> 
    return; // this exits the script 
... 
... 



})(); // this calls the whole script as a single function 
相关问题