Is there a way to exit a Greasemonkey script?

大憨熊 提交于 2019-12-06 11:24:27

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.

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.

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