我想在用户离开页面之前做一个确认。如果他说ok,那么它将重定向到新的页面或取消离开。我试着用onunload来做

<script type="text/javascript">
function con() {
    var answer = confirm("do you want to check our other products")
    if (answer){

        alert("bye");
    }
    else{
        window.location = "http://www.example.com";
    }
}
</script>
</head>

<body onunload="con();">
<h1 style="text-align:center">main page</h1>
</body>
</html>

但它确认后,页面已经关闭?如何正确地做呢?

如果有人展示如何用jQuery来做,那就更好了。


当前回答

您可以使用下面的一行程序在离开页面之前始终询问用户。

window.onbeforeunload = s => "";

若要询问用户页面上的内容何时被修改,请参阅此回答。

其他回答

这就是我所做的显示确认消息,只是当我有未保存的数据

window.onbeforeunload = function() {
  if (isDirty) {
    return 'There is unsaved data.';
  }
  return undefined;
}

返回undefined将禁用确认

注意:返回null将不能在IE中工作

您还可以使用undefined禁用确认

window.onbeforeunload = undefined;

为了有一个弹出Chrome 14+,你需要做以下:

jQuery(window).bind('beforeunload', function(){
    return 'my text';
});

用户将被问及他想要留下还是离开。

<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">

<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>

<script>
function myFunction() {
    return "Write something clever here...";
}
</script>

</body>
</html>

https://www.w3schools.com/tags/ev_onbeforeunload.asp

您可以使用下面的一行程序在离开页面之前始终询问用户。

window.onbeforeunload = s => "";

若要询问用户页面上的内容何时被修改,请参阅此回答。

这里的大多数解决方案都不适合我,所以我使用了这里找到的解决方案

我还添加了一个变量来确定是否允许确认框

window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
    if (!hideWarning) {
        event.preventDefault();
        event.returnValue = '';
    }

});