jQuery beforeunload 事件未在后退按钮上触发

jQuery beforeunload event not firing on back button

本文关键字:按钮 beforeunload 事件 jQuery      更新时间:2023-09-26

我有一个主干应用程序,我想在导航离开未保存的更改之前提醒用户。我有一个活动要做:

$(window).bind('beforeunload', function() {
    var status = {
        unsavedEdits: false
    };
    Backbone.trigger('producerApp:navigate', status);
    if (status.unsavedEdits) {
        return status.msg || 'There are unsaved edits. Continuing will discard these edits.';
    }
});

问题是单击后退按钮时,Chrome不会触发此功能。我没有读到任何表明应该如此的内容。这里有问题吗?

只要与

页面有初始交互,此代码也应该适用于后退按钮。

window.onbeforeunload = function(){
return "are you sure you want to navigate away?";
}

注意:为了防止不需要的弹出窗口,浏览器可能不会显示 beforeunload 事件处理程序中创建的提示,除非页面已与之交互,甚至可能根本不显示它们。

这是来自 https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

编辑:

$(document).ready(function() {
  $(window).bind('beforeunload', function() {
    var status = {
      unsavedEdits: true
    };
    if (status.unsavedEdits) {
      return 'There are unsaved edits. Continuing will discard these edits.';
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

我认为事件在卸载之前正在进行

使用这个。在我的机器上试用过。成功了。