Javascript 当我关闭浏览器时确认对话框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4427714/
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
Confirm Dialog when i close the browser?
提问by chittibabu
i need to display confirm dialog box before close browser window using javascript or PHP. the confirm box should come when i click the close button of browser. other wise don't display dialog. please help me any.
我需要在使用 javascript 或 PHP 关闭浏览器窗口之前显示确认对话框。当我点击浏览器的关闭按钮时,确认框应该出现。否则不显示对话框。请帮助我。
回答by ivy
You should handle the onbeforeunload event...
您应该处理 onbeforeunload 事件...
function closeEditorWarning(){
return 'Are you sure?'
}
window.onbeforeunload = closeEditorWarning;
Or use jquery, window.attachEvent / window.addEventListener to do it nicely
或者使用jquery, window.attachEvent / window.addEventListener 做的很好
回答by Dan Beam
onunload
is not very useful (in my opinion) as you can't doanything with the confirm
ation you're requesting (except maybe attempt to new another window with window.open
, so onbeforeunload
is more useful for this case.
onunload
不是很有用(在我看来),因为你不能对你请求的ation做任何事情confirm
(除非尝试用 新建另一个窗口window.open
,所以onbeforeunload
在这种情况下更有用。
Your better bet is onbeforeunload
, which is great but won't work in Opera (though this usually isn't a deal breaker).
更好的选择是onbeforeunload
,这很好,但在 Opera 中不起作用(尽管这通常不会破坏交易)。
Like ivy said, it would look something like this:
就像常春藤所说,它看起来像这样:
<script>
var userIsEditingSomething; // set this if something crazy happens
oldOnBeforeUnload = window.onbeforeunload;
window.onbeforeunload = function () {
// attempt to handle a previous onbeforeunload
if ('function' === typeof oldOnBeforeUnload) {
var message = oldOnBeforeUnload();
if ('undefined' !== typeof message) {
if (confirm('string' === typeof message ? message : 'Are you sure you want to leave this page?')) {
return; // allow user to exit without further annoying pop-ups
}
}
}
// handle our own
if (userIsEditingSomething) {
return 'Are you sure you want to exit?';
}
};
</script>
回答by Bhanu Prakash Pandey
function doUnload()
{
// use confirm dialog box here
confirm("Window is closing...");
}
<body onunload="doUnload()">