javascript Javascript检测浏览器关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21430884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript detect browser close
提问by RubenHerman
Is it possible to detect if the browser is closing in JavaScript? I tried using:
是否可以检测浏览器是否在 JavaScript 中关闭?我尝试使用:
$( window ).unload(function() {
//Code
});
and:
和:
window.onbeforeunload = ExecuteMyCode;
function ExecuteMyCode() {
//Code
}
But this both executes when we also click a link, button,... I ONLY want to detect the browser close event.
但是,当我们还单击链接、按钮时,这两者都会执行……我只想检测浏览器关闭事件。
回答by Dhaval trivedi
You can try below code it will ensure your mouse position is on the close button then and then it will execute further.
您可以尝试下面的代码,它会确保您的鼠标位置在关闭按钮上,然后它将进一步执行。
window.onbeforeunload = function () {
if (event.clientY < 0) {
// DO YOUR STUFF BEFORE CLOSING..
}
return "Message to display user before close.";
}
}