如何通过单击Chrome中的标签在离开网站之前显示警告消息?

时间:2019-05-23 07:22:08

标签: javascript function tabs

我正在尝试在关闭选项卡之前警告用户。我在很多地方搜索了正确的代码,但似乎在chrome中不起作用。

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        return "You have attempted to leave this page. Are you sure?";
    }
</script>

在IE中可以正常工作。我不需要显示任何自定义消息。我只需要警告用户他们将离开网站。知道为什么这行不通吗?还有其他方法可以强制浏览器在离开网站之前显示警告吗?

编辑:我使用的是Google Chrome 74.0.3729.169

enter image description here

3 个答案:

答案 0 :(得分:0)

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

答案 1 :(得分:0)

使用confirm()函数:

function confirmExit(e) {
  if (!confirm("You have attempted to leave this page. Are you sure?")) {
    e.preventDefault();
    return false;
  }
}

答案 2 :(得分:0)

由于@barbsan,我找到了解决方案。他提供的链接包含解决方案。

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

        (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
        return confirmationMessage;                                //Webkit, Safari, Chrome etc.
 });

https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent