Is there a way to exit a Greasemonkey script?

ε祈祈猫儿з 提交于 2019-12-08 02:20:40

问题


I know that you can use return; to return from a Greasemonkey script, but only if you aren't in another function. For example, this won't work:

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

Is there a built in Greasemonkey function that would allow me to halt execution of the script, from anywhere in the script?

Thank you,


回答1:


Yeah, you can probably do something like:

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

You can simply abort your script by setting the value of variable parameter to abort, this can either be a regular variable or a Greasemonkey variable. If it's a Greasemonkey variable, then you can modify it directly through the browser using about:config in Firefox.




回答2:


Is there a built in Greasemonkey function that would allow me to halt execution of the script, from anywhere in the script?

No. These are the current Greasemonkey functions.


You can throw an exception, like Anders' answer, but I prefer not to exception-out except in exceptional circumstances.

There's always the old classic, 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


Alternatively, you could use function returns instead of the local global.




回答3:


If you are inside a nested call of functions, throw seems like the only solution to quit the script all together. However, if you want to quit the script somewhere within the script (not inside a function call), I suggest wrapping all the script into an anonymous function.

// 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


来源:https://stackoverflow.com/questions/4651452/is-there-a-way-to-exit-a-greasemonkey-script

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