Chrome和Firefox的onbeforeunload问题

时间:2014-05-19 15:30:42

标签: javascript google-chrome firefox alert confirmation

在过去的几天里,我注意到在离开我的网页之前我应该​​看到的确认提醒不会再显示在Chrome和Firefox上,但它会在IE上显示。 如果我使用谷歌Chrome开发工具调试,我可以看到执行功能确认,输入if语句,但没有显示警告框。我尝试重新启动Google Chrome并查找重置警报消息的选项,但我一无所获。 有什么想法吗?

代码是这样的:

if (window.addEventListener) {
                    window.addEventListener('beforeunload', confirm, false);
                }
                else window.attachEvent("onbeforeunload", confirm);

...

function confirm(e) {
    if (changed== true) {
        return "You haven't saved your changes!";
    }
}

2 个答案:

答案 0 :(得分:1)

我找到了一个有效的解决方案,但实际上我并不理解为什么attachEvent不再有效。无论如何,这是在IE,Chrome和Firefox上测试的可行解决方案:

我删除了addEventListener和attachEvent行:

/* if (window.addEventListener) {
                    window.addEventListener('beforeunload', confirm, false);
                }
                else window.attachEvent("onbeforeunload", confirm); */

在HTML中,我将onbeforeunload属性添加到body标签:

<body onbeforeunload="return confirmEvent()">

我还重命名了onbeforeunload函数,以避免与确认的内置javascript函数混淆:

function confirmEvent(e) {
    if (changed== true) {
        return "You haven't saved your changes!";
    }
}

答案 1 :(得分:1)

请参阅How to detect the dragleave event in Firefox when dragging outside the window

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  e.returnValue = confirmationMessage;     // Gecko and Trident
  return confirmationMessage;              // Gecko and WebKit
});

在我测试的每个浏览器中工作;)

PS:我知道它有点迟了