jQuery 如何在离开页面时控制浏览器确认对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19179514/
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-26 23:22:49  来源:igfitidea点击:

How to control browser confirmation dialog on leaving page?

javascriptjquery

提问by Noah Martin

I know there are a lot of questions regarding this but nothing is answering me right. I want to show a confirmation dialog when user leaves the page. If the user press Cancel he will stay on page and if OK the changes that he has made will be rollback-ed by calling a method. I have done like this:

我知道对此有很多问题,但没有什么能正确回答我。我想在用户离开页面时显示一个确认对话框。如果用户按取消,他将留在页面上,如果确定,他所做的更改将通过调用方法回滚。我这样做了:

window.onbeforeunload = function () {
  var r = confirm( "Do you want to leave?" );
  if (r == true) {
       //I will call my method
  }
  else {
      return false;
  }
};

The problem is that I am getting the browser default popup: "LeavePage / StayOnPage"

问题是我得到了浏览器默认弹出窗口:“LeavePage/StayOnPage”

This page is asking you to confirm that you want to leave - data you have entered may not be saved.

此页面要求您确认是否要离开 - 您输入的数据可能不会被保存。

This message is shown in Firefox, in Chrome is a little different. I get this popup after I press OK on my first confirmation dialog.

此消息在 Firefox 中显示,在 Chrome 中略有不同。在我的第一个确认对话框中按 OK 后,我得到了这个弹出窗口。

Is there a way not to show this dialog? (the second one, that I did not create). Or if there is any way to control this popup, does anyone know how to do that? Thanks

有没有办法不显示这个对话框?(第二个,我没有创建)。或者如果有任何方法可以控制这个弹出窗口,有没有人知道怎么做?谢谢

采纳答案by Thor Jacobsen

Here's what I've done, modify to fit your needs:

这是我所做的,根据您的需要进行修改:

// This default onbeforeunload event
window.onbeforeunload = function(){
    return "Do you want to leave?"
}

// A jQuery event (I think), which is triggered after "onbeforeunload"
$(window).unload(function(){
    //I will call my method
});

Note: it's tested to work in Google Chrome, IE8 and IE10.

注意:它经过测试可以在 Google Chrome、IE8 和 IE10 中工作。