Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 676
Noah Martin Avatar asked Oct 04 '13 10:10

Noah Martin


2 Answers

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.

like image 113
Dennis He Avatar answered Nov 09 '22 02:11

Dennis He


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.

like image 24
Thor Jacobsen Avatar answered Nov 09 '22 03:11

Thor Jacobsen