我想在用户离开页面之前做一个确认。如果他说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来做,那就更好了。


当前回答

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

<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>

其他回答

为了有一个弹出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

Onunload(或onbeforeunload)不能将用户重定向到另一个页面。这是出于安全考虑。

如果你想在用户离开页面之前显示一个提示,使用onbeforeunload:

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

或者使用jQuery:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

这只会询问用户是否想要离开页面,如果他们选择留在页面上,你不能重定向他们。如果他们选择离开,浏览器会去他们告诉它去的地方。

你可以使用onunload在页面卸载之前做一些事情,但你不能从那里重定向(Chrome 14+块警报内onunload):

window.onunload = function() {
    alert('Bye.');
}

或者使用jQuery:

$(window).unload(function(){
  alert('Bye.');
});

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

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

通常情况下,当用户在表单中进行了更改,但这些更改没有保存时,您希望显示此消息。

采用这种方法只在用户更改某些内容时才显示消息

var form = $('#your-form'),
  original = form.serialize()

form.submit(function(){
  window.onbeforeunload = null
})

window.onbeforeunload = function(){
  if (form.serialize() != original)
    return 'Are you sure you want to leave?'
}