离开页面前的 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7080269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:46:19  来源:igfitidea点击:

JavaScript before leaving the page

javascriptjquery

提问by kd7

I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload

我想在用户离开页面之前进行确认。如果他说好,那么它会重定向到新页面或取消离开。我试着用 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>

But it confirm after page already closed? How to do it properly?

但是它在页面已经关闭后确认?如何正确操作?

It would be even better if someone shows how to do it with jQuery?

如果有人展示如何用 jQuery 做到这一点会更好吗?

回答by Rocket Hazmat

onunload(or onbeforeunload) cannot redirect the user to another page. This is for security reasons.

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

If you want to show a prompt before the user leaves the page, use onbeforeunload:

如果要在用户离开页面之前显示提示,请使用onbeforeunload

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

Or with jQuery:

或者使用 jQuery:

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

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

这只会询问用户是否要离开页面,如果他们选择留在页面上,则无法重定向他们。如果他们选择离开,浏览器将转到他们告诉它去的地方。

You can use onunloadto do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

您可以onunload在页面卸载之前执行某些操作,但无法从那里重定向(Chrome 14+ 会阻止内部警报onunload):

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

Or with jQuery:

或者使用 jQuery:

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

回答by Wasim A.

This code when you also detect form state changed or not.

当您还检测表单状态更改与否时,此代码。

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

You can Google JQuery Form Serialize function, this will collect all form inputs and save it in array. I guess this explain is enough :)

您可以使用 Google JQuery Form Serialize 函数,这将收集所有表单输入并将其保存在数组中。我想这个解释就足够了:)

回答by Ajit Singh

This will alert on leaving current page

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

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

回答by Mina Matta

This what I did to show the confirmation message just when I have unsaved data

这是我在有未保存数据时显示确认消息的操作

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

returning "undefined" will disable the confirmation

返回“未定义”将禁用确认

Note: returning "null" will not work with IE

注意:返回“null”不适用于 IE

Also you can use "undefined" to disable the confirmation

您也可以使用“未定义”来禁用确认

window.onbeforeunload = undefined;

回答by David Bélanger

In order to have a popop with Chrome 14+, you need to do the following :

为了在 Chrome 14+ 上使用 popop,您需要执行以下操作:

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

The user will be asked if he want to stay or leave.

将询问用户是要留下还是离开。

回答by spencer.sm

You can use the following one-liner to alwaysask the user before leaving the page.

您可以使用以下单行代码在离开页面之前始终询问用户。

window.onbeforeunload = s => "";

To ask the user when something on the page has been modified, see this answer.

要询问用户何时修改了页面上的某些内容,请参阅此答案

回答by Simon Franzen

Normally you want to show this message, when the user has made changes in a form, but they are not saved.

通常,您希望在用户对表单进行更改但未保存时显示此消息。

Take this approach to show a message, only when the user has changed something

采取这种方法来显示消息,仅当用户更改某些内容时

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?'
}

回答by Emir Mamashov

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

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

回答by l2aelba

Just a bit more helpful, enableand disable

只是更有帮助,启用禁用

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

回答by Raj Sharma

Most of the solutions here did not work for me so I used the one found here

此处的大多数解决方案对我都不起作用,因此我使用了此处找到的解决方案

I also added a variable to allow the confirm box or not

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

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

});