2011-01-10 129 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 
相關問題