Javascript 关闭浏览器窗口之前的javascript确认对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6966319/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:00:47  来源:igfitidea点击:

javascript confirm dialog box before close browser window

javascript

提问by user881851

I need to display a confirm dialog box before closing the browser window using javascript or PHP. The confirm box should come up when I click the close button of browser; otherwise, the dialog should not be displayed.

我需要在使用 javascript 或 PHP 关闭浏览器窗口之前显示一个确认对话框。当我点击浏览器的关闭按钮时,确认框应该出现;否则,不应显示该对话框。

Thanks

谢谢

回答by Marcus Granstr?m

This will display it when closing the browser:

这将在关闭浏览器时显示:

window.onbeforeunload = function (event) {
  var message = 'Sure you want to leave?';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}

回答by Govind Malviya

Use this code , I used that earlier, I here

使用此代码,我之前使用过,我在这里

<html>
<head>
<title>.:I 0wn U:.</title>
<script language="JavaScript">
<!--
window.onbeforeunload = bunload;

function bunload(){
dontleave="Are you sure you want to leave?";
return dontleave;
}
//-->
</script>
</head>
<body>
Please stay on this page!
</body>
</html>

回答by Justo

With Jquery:

使用jQuery:

$(window).bind('beforeunload', function(e) {
    // Your code and validation
    if (confirm) {
        return "Are you sure?";
    }
});