使用onbeforeunload函数内的自定义对话框确认重新加载页面.在弹出框之前在函数onbeforeunload中执行的代码

Har*_*ama 4 javascript jquery confirm reload

我想在用户尝试重新加载页面时显示一个确认框.我在我的项目中尝试过它并没有用.我已经创建了一个我尝试过的示例代码,即使它不起作用.任何人都可以告诉我哪里出错了.我甚至没有收到确认框.我使用的是Chrome 33+.我需要在弹出框之前在window.onbeforeunload中执行一些代码.

<!DOCTYPE>
<html>
<body>
    <script type="text/javascript">
        window.onbeforeunload = function()
        {
          var r = confirm("Are you sure you want to reload the page.");
          if(r)
          {
            window.location.reload();
          }
          else
          {

          }
        };

    </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Jon*_*t92 5

这将有效:

 window.onbeforeunload = function ()
 {
     return "";
 };
Run Code Online (Sandbox Code Playgroud)

最新版本的Chrome(可能还有其他一些版本)不支持任何内容,只是在使用时返回一条简单的消息onbeforeunload.功能中的其他代码似乎被忽略,至少在Chrome中是这样.

会为你做的伎俩.您可以返回与空字符串不同的内容(使其成为自定义),但这会导致重复的问题(您的消息+浏览器提供的消息),但没有什么能阻止您这样做.

在IE9和最新版Chrome中测试过.它将启动一个警告框,询问用户是否要重新加载.