页面中的条件onbeforeunload事件

13
window.onbeforeunload = function(evt) {
    var message = 'Are you sure you want to leave the page. All data will be lost!';

    if (typeof evt === 'undefined') {
        evt = window.event;
    }
    if (evt && !($("#a_exit").click)) {
        evt.returnValue = message;
    }
    return message;
};

我希望用户只能通过点击链接(具有id ="a_exit")离开页面。在其他情况下,如刷新页面、单击另一个链接,用户将被提示是否要离开页面。我已尝试使用上面的代码,但当我单击退出链接时仍会询问我是否要离开。

8个回答

5
$(window).bind('beforeunload',function() {
    return "'Are you sure you want to leave the page. All data will be lost!";
});

$('#a_exit').live('click',function() {
    $(window).unbind('beforeunload');
});

以上对我有效。

4

在离开页面之前,我的快速条件提示示例:

    window.onbeforeunload = confirmExit;
    function confirmExit(event) {
        var messageText = tinymce.get('mMessageBody').getContent();
        messageText = messageText.trim();

        // ... whatever you want

        if (messageText != "")
            return true;
        else
            return void (0);
   };

它可以在Chrome和FF浏览器下使用。


非常感谢。在IE9和Safari中都可以正常运行。对于旧版浏览器,请使用以下行替代返回true以发送自定义消息。 return _isSaved ? void (0) : "您在此窗口上有未保存的工作。" - Pandi_Snkl

4

当您不想显示提示时,可以返回 null。 在Chrome 79上测试通过。

window.onbeforeunload = () =>  {
    if(shouldPrompt){
       return true
    }else{
       return null
    }
}

顺便提一下,现代浏览器不再支持自定义的onBeforeUnload提示文本。


2

2
最初的回答对我很有帮助。
这对我管用。
   window.onbeforeunload = function(){
    if(someBoolean) {
    return 'message'
    }else{
    window.onbeforeunload = null;
    }
    }

这在IE11上也有效,而返回null则无效。 - Ciaran

1

您可以在单击处理程序中删除 window.onbeforeunload


2
我猜想它不会起作用,但在最新的Chrome、IE和FF下进行了测试,它可以正常工作 http://jsfiddle.net/Suf99/ - A. Wolff

0

这个问题很老了,但是我想改变代码,因为在Jquery中.live已经不再起作用了。所以,更新后的版本应该是:

$(window).bind('beforeunload',function() {
     return "'Are you sure you want to leave the page. All data will be lost!";
 });

 $('#a_exit').on("click", function(){
    $(window).unbind('beforeunload');
});

0

加一个变量来判断链接是否被点击了怎么样?

var exitClicked = false;

$("#a_exit").click(function() {
  exitClicked = true;
});

window.onbeforeunload = function(evt) {
  //...

  if(evt && !exitClicked) {
    evt.returnValue = message;
  }  

  //...
};

你只有在链接真正被点击后才会设置exitClicked = true,在卸载之前你可以简单地检查这个变量。该内容与编程有关。

1
抱歉,这并没有改变任何事情。 - zkanoca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接