我如何退出JavaScript脚本,就像PHP的退出或死亡?我知道这不是最好的编程实践,但我需要这样做。


JavaScript相当于PHP的die。顺便说一句,它只是调用exit()(谢谢splattne):

function exit( status ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // +      input by: Paul
    // +   bugfixed by: Hyam Singer (http://www.impact-computing.com/)
    // +   improved by: Philip Peterson
    // +   bugfixed by: Brett Zamir (http://brettz9.blogspot.com)
    // %        note 1: Should be considered expirimental. Please comment on this function.
    // *     example 1: exit();
    // *     returns 1: null

    var i;

    if (typeof status === 'string') {
        alert(status);
    }

    window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);

    var handlers = [
        'copy', 'cut', 'paste',
        'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',
        'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',
        'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'
    ];

    function stopPropagation (e) {
        e.stopPropagation();
        // e.preventDefault(); // Stop for the form controls, etc., too?
    }
    for (i=0; i < handlers.length; i++) {
        window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);
    }

    if (window.stop) {
        window.stop();
    }

    throw '';
}

If you're looking for a way to forcibly terminate execution of all Javascript on a page, I'm not sure there is an officially sanctioned way to do that - it seems like the kind of thing that might be a security risk (although to be honest, I can't think of how it would be off the top of my head). Normally in Javascript when you want your code to stop running, you just return from whatever function is executing. (The return statement is optional if it's the last thing in the function and the function shouldn't return a value) If there's some reason returning isn't good enough for you, you should probably edit more detail into the question as to why you think you need it and perhaps someone can offer an alternate solution.

注意,在实践中,大多数浏览器的Javascript解释器在遇到错误时会简单地停止运行当前脚本。所以你可以做一些事情,比如访问一个未设置变量的属性:

function exit() {
    p.blah();
}

它可能会中止脚本。但你不应该指望它,因为它根本不是标准的,而且它看起来真的是一个糟糕的做法。

编辑:好吧,也许这不是一个很好的答案Ólafur的光。尽管他链接到的die()函数基本上实现了我的第二段,即它只是抛出一个错误。


"exit"函数通常退出程序或脚本,并以错误消息作为参数。例如php中的die(…)

die("sorry my fault, didn't mean to but now I am in byte nirvana")

在JS中等效的是用throw关键字发出错误信号,如下所示:

throw new Error();

你可以很容易地测试这个:

var m = 100;
throw '';
var x = 100;

x
>>>undefined
m
>>>100

即使在没有句柄、事件等的简单程序中,最好将代码放在主函数中,即使它是唯一的过程:

<script> 
function main()
{
//code

}
main();
</script>

这样,当你想要停止程序时,你可以使用return。


放置调试器;关键字,在你想要停止执行的JavaScript代码。然后打开您喜欢的浏览器的开发人员工具并重新加载页面。现在它应该自动暂停。打开工具的Sources部分:调试器;关键字高亮显示,您可以选择恢复脚本执行。

我希望这能有所帮助。

更多信息请浏览:

https://developer.mozilla.org/de/docs/Tools/Debugger http://www.w3schools.com/js/js_debugging.asp


在我的例子中,我使用window.stop。

window.stop()在当前浏览上下文中停止进一步的资源加载,相当于浏览器中的'stop'按钮。 由于脚本的执行方式不同,此方法不能中断其父文档的加载,但它将停止其父文档的图像、新窗口和其他仍在加载的对象。 用法:window.stop (); (源)


如果你不关心它是一个错误,可以这样写:

fail;

这将阻止您的主(全局)代码继续进行。 对调试/测试的某些方面很有用。


这是一个例子, 如果条件存在,则终止脚本。 我使用这个在我的SSE客户端javascript,如果

<script src="sse-clint.js" host="https://sse.host" query='["q1,"q2"]' ></script>

不能直接从JSON解析…

if( ! SSE_HOST  ) throw new Error(['[!] SSE.js: ERR_NOHOST - finished !']);

... 总之,总的思想是:

if( error==true) throw new Error([ 'You have This error' ,  'At this file', 'At this line'  ]);

这将终止/死亡你的javascript脚本


退出JS或Node脚本的方法有很多。以下是最相关的:

// This will never exit!
setInterval((function() {  
    return;
}), 5000);

// This will exit after 5 seconds, with signal 1
setTimeout((function() {  
    return process.exit(1);
}), 5000);

// This will also exit after 5 seconds, and print its (killed) PID
setTimeout((function() {  
    return process.kill(process.pid);
}), 5000);

// This will also exit after 5 seconds and create a core dump.
setTimeout((function() {  
    return process.abort();
}), 5000);

如果你在REPL中(即在命令行上运行node之后),你可以输入.exit退出。


这个小函数非常接近于模仿PHP的exit()。与其他解决方案一样,不要添加任何其他解决方案。

function exit(Msg)
    {
    Msg=Msg?'*** '+Msg:'';
    if (Msg) alert(Msg);
    throw new Error();
    } // exit

简单地创建一个BOOL条件, 这里不需要复杂的代码。

即使你把它变成true/或多次, 它会给你一条解,而不是多条解 基本上就是这么简单。


把“”;

是对这个概念的误用,但可能是唯一的选择。是的,您必须重置所有事件侦听器,就像接受的答案提到的那样。如果我是对的,你还需要一个单一的入口。

在它的顶部:你想要一个通过电子邮件向你报告的页面,你可以使用例如Raven/Sentry。但这意味着,你给自己制造了假阳性。在这种情况下,您还需要更新默认处理程序以过滤掉此类事件,或者在Sentry的仪表板上将此类事件设置为忽略。

window.stop ();

这在页面加载期间不起作用。它也会停止对页面的解码。所以你不能用它来为用户提供网页的无javascript变体。

调试器;

仅在调试器打开时停止执行。工作很好,但不能交付。


我想这个问题已经有答案了,点击这里了解更多信息。下面是它发布的简短答案。

throw new Error("Stop script");

您也可以使用您的浏览器添加断点,每个浏览器都是类似的,检查以下信息为您的浏览器。

为Chrome断点信息点击这里 有关Firefox断点信息,请点击这里 有关资源管理器断点信息,请单击 有关Safari断点信息,请点击这里


如果你在脚本中使用任何未定义的函数,那么脚本将由于“Uncaught ReferenceError”而停止。我已经尝试了以下代码和执行的前两行。

我认为,这是停止剧本的最好方法。如果有任何其他方式,请评论我。我还想知道另一种最好最简单的方法。BTW,我没有得到退出或死亡内置函数在Javascript像PHP终止脚本。如果有人知道,请告诉我。

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');

我使用return语句而不是throw,因为throw在控制台给出错误。最好的办法是检查情况

if(condition){
 return //whatever you want to return
}

这只是从这一行停止程序的执行,而不是在控制台中给出任何错误。


我使用这段代码来停止执行:

throw new FatalError("!! Stop JS !!");

虽然你会得到一个控制台错误,但这对我来说很好。


如果你只是想停止执行更多的代码而不“抛出”任何错误,你可以暂时覆盖window。如cross-exit所示:

function exit(code) {
    const prevOnError = window.onerror
    window.onerror = () => {
        window.onerror = prevOnError
        return true
    }

    throw new Error(`Script termination with code ${code || 0}.`)
}

console.log("This message is logged.");
exit();
console.log("This message isn't logged.");

在JavaScript中有多种方式,下面是其中的一些

方法1:

throw new Error("Something went badly wrong!");

方法2:

return;

方法3:

return false;

方法4:

new new

方法5:

使用上述方法编写自定义函数,并在需要的地方调用

注意: 如果您想暂停代码执行,您可以使用

debugger; 

我使用ibroker和容易地设法停止脚本

stopScript();

在大多数情况下不适用,但我有很多异步脚本在浏览器中运行,作为一个hack我做

window.reload();

停止一切。


我知道这是旧的,但如果你想要一个类似的PHP die()函数,你可以这样做:

function die(reason) {
    throw new Error(reason);
}

用法:

console.log("Hello");
die("Exiting script..."); // Kills script right here
console.log("World!");

上面的例子只打印“Hello”。


这段代码将停止当前窗口中所有javascript的执行:

(,);

例子

console.log('READY!'); setTimeout(()=>{ /* animation call */ div.className = "anim"; console.log('SET!'); setTimeout(()=>{ setTimeout(()=>{ console.log('this code will never be executed'); },1000); console.log('GO!'); /* BOMB */ for(;;); console.log('this code will never be executed'); },1000); },1000); #div { position: fixed; height: 1rem; width: 1rem; left: 0rem; top: 0rem; transition: all 5s; background: red; } /* this <div> will never reached the right bottom corner */ #div.anim { left: calc(100vw - 1rem); top: calc(100vh - 1rem); } <div id="div"></div>


Javascript可以在devtools中禁用:ctrl+shift+j跟随cltf+shift+p,然后输入disable Javascript

上述可能的选项:

window.stop(); // equivalent to the 'stop' button in the browser
debugger; // debugs
for(;;); // crashes your browser
window.location.reload(); // reloads current page

如果页面已加载,而你不想调试崩溃或重新加载:

throw new Error();

此外,清除所有超时

var id = window.setTimeout(function() {}, 0);
while (id--) {
    window.clearTimeout(id);
}

中止DOM - XMLHttpRequest

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(i, jqXHR) { 
        jqXHR.abort();  
        $.xhrPool.splice(i, 1); 
    });
}
$.ajaxSetup({
    beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); },
    complete: function(jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR);
        if (i > -1) $.xhrPool.splice(i, 1); 
    }
});

删除所有事件监听器,包括内联监听器

$("*").prop("onclick", null).off();

这将删除脚本并重新创建没有事件的元素

$('script').remove();
$('*').each(function(){
    $(this).replaceWith($(this).clone());   
});

如果网页上没有jQuery,则复制粘贴源代码到控制台。

可能还有其他的东西。请在评论中告诉我。


要停止脚本执行而不出现任何错误,可以将所有脚本包含到函数中并执行它。 这里有一个例子: (函数(){ console.log(一); 返回; console.log(两个); }) ();

上面的脚本将只记录一个日志。

在使用前

如果您需要在脚本本身之外读取脚本的函数,请记住(通常)这是行不通的:要做到这一点,您需要使用一个预先存在的变量或对象(您可以将函数放在窗口对象中)。 上面的代码可能是你不想要的:将整个脚本放在一个函数中可能会产生其他后果(例如,这样做,脚本将立即运行,并且没有办法从浏览器开发中修改其部分,正如我所知道的,在Chrome中)


带有函数的Wrapp

(function(){
alert('start')

return;
alert('no exec')
})