简体   繁体   中英

How to control browser confirmation dialog on leaving page?

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"

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.

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

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.

This is simple. Just use

window.onbeforeunload = function(){
  return '';
};

to prompt when the user reloads, and

window.close = function(){
 return '';
};

to prompt when the user closes the page. But the user have to click on the page once, or do anything on the page for the code to detect. You don't have to put anything the the return''; , because JavaScript interpreter would just ignore it.

 window.onbeforeunload = function() {
       if (data_needs_saving()) {
           return "Do you really want to leave our brilliant application?";
       } else {
          return;
       }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM