在 Rails 中,onbeforeunload 在 Chrome 浏览器中不一致

In Rails, onbeforeunload not working consistently for Chrome browser

我正试图让 onbeforeunload 在我的页面上始终如一地工作,该页面有用户正在填写的表单。我期待以下内容:

我目前正在 Google Chrome 下进行测试,我现在正在使用以下内容 - 虽然我已经尝试了一些变体。

<script>

  $(document).on('ready page:load', function () {
    $(window).on('beforeunload', function() {
      return "You should keep this page open.";
    });
  });

</script>

我有时会收到提示,但不是始终如一。我认为这可能与上面的代码和 turbolinks 有冲突。但一直未能找到解决方法来获得上述预期结果。

--- 更新:

这是我最终使用的代码。

<script data-turbolinks-eval="false">

$(document).ready(function() {
  form_modified=0;

  $('#report-form *').change(function(){
     form_modified=1;
  });

  $("#report-form input[name='commit']").click(function() {
      form_modified = 0;
  });
});

$(document).on('page:before-change', function() {

  if ($("#report-form").length > 0) {
    if (form_modified==1) {
      if (confirm("There are unsaved changes, click \"Cancel\" to remain on the page.")) {
        // clicks "OK", nothing here means
      } else {
        // clicks "Cancel"
        event.preventDefault();
      }
    }
  }
});

</script>

此方法不适用于 window "X" 页面刷新或退出,但是...

Turbolinks 为这种情况提供了 page:before-change 事件。

不过,我不确定为什么要将第二个处理程序 绑定到 第一个处理程序中。当您单击 Turbolinks link.

时,window 对象不会改变