我想在用户离开页面之前做一个确认。如果他说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 = function() {
  if (isDirty) {
    return 'There is unsaved data.';
  }
  return undefined;
}

返回undefined将禁用确认

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

您还可以使用undefined禁用确认

window.onbeforeunload = undefined;

其他回答

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

window.onbeforeunload = s => "";

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

只是更有用一点,启用和禁用

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

这将在离开当前页面时发出警报

<script type='text/javascript'>
function goodbye(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye; 

</script>

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

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

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

});

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

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

返回undefined将禁用确认

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

您还可以使用undefined禁用确认

window.onbeforeunload = undefined;