如何要求用户确认他们要离开页面?

时间:2018-01-25 18:32:41

标签: javascript cross-browser onbeforeunload

我的网站包含多个页面,用户可以在其中添加和编辑信息。为了提供一致的UI,我有以下JavaScript函数...

function setWindowBeforeUnload(changed) {
  $(window).on("beforeunload", function() {
    if (confirmLeave && changed && changed()) {
      return "You haven't saved the information. If you leave this page, the information will be lost.";
    }
  });
}

confirmLeave是一个全局变量,它指定我们是否要在导航之前要求他们进行确认(如果我们在成功保存后导航到另一个页面则不会这样做)。 changed是一个检查实体是否已更改的函数。

这是从详细信息页面(比如客户页面)调用,如下所示......

$(document).ready(function() {
  setWindowBeforeUnload(customerChanged);
});

function customerChanged() {
  // Checks the data and returns true or false as appropriate
}

直到最近,当change in Chrome打破它时,一切正常。

我已经搜索了几个小时,发现有很多人建议像这样的代码...

addEventListener('beforeunload', function(event) {
  event.returnValue = 'You have unsaved changes.';
});

...它可以正常工作,只要它在离开页面时触发警告,无论数据是否发生了变化。

一旦我尝试添加任何逻辑(例如我在第一个样本中的检查代码),它就不起作用......

function setWindowBeforeUnload(changed) {
  addEventListener('beforeunload', function(event) {
    if (confirmLeave && changed && changed()) {
      event.returnValue = 'You have unsaved changes.';
    }
  });
}

使用此代码,我可以离开页面而不会收到警告。

现在有没有办法重现我原来的行为?

1 个答案:

答案 0 :(得分:1)

您可以在处理程序中使用逻辑,您不能再拥有自定义消息了。 请参阅下面的代码。使用“运行代码段”来模拟导航。运行代码段,再次运行它没有确认。将按钮切换为“false”运行代码段并获得确认。

var test = true;

function otherTest() {
  return true;
}

addEventListener('beforeunload', function(event) {
if(!test || !otherTest()) {
  event.returnValue = 'You have unsaved changes.';
}
  
});

document.getElementById('theButton').addEventListener('click', function(event) {
  test = !test;
  this.innerHTML = test.toString();
});
<p>Click the button to turn the confirm on and off</p>
<button id="theButton">true</button>

相关问题