Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onbeforeunload confirmation screen customization

Is it possible to create a custom confirmation box for the onbeforeunload event in a browser? I tried but then I get 2 confirmation boxes (one from me which is nothing more than return confirm... and then the standard one from the browser).

At the moment my code looks like:

var inputChanged = false;

$(window).load(function() {
    window.onbeforeunload = navigateAway;
    $(':input').bind('change', function() { inputChanged = true; });
});

function navigateAway(){
    if(inputChanged){
        return 'Are you sure you want to navigate away?';
    }
}

I'm using jQuery for this.

like image 341
Nyla Pareska Avatar asked Aug 26 '09 15:08

Nyla Pareska


2 Answers

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

Please note: Most browsers put this message after some other text. You do not have complete control of the content of the confirmation dialog.

like image 188
Eli Grey Avatar answered Oct 18 '22 21:10

Eli Grey


No, you can't avoid the standard one from the browser. All you can do is inject some custom text into it; if you use the following event handler (registered the prototype lib way):

Event.observe(window, "beforeunload", function(event) {
    if (showMyBeforeUnloadConfirmation)
        event.returnValue = "foo bar baz";
});

(and showMyBeforeUnloadConfirmation is true) you'll get the browser's standard confirmation with the following text:

Are you sure you want to navigate away from this page?

foo bar baz

Press OK to continue, or Cancel to stay on the current page.

[ OK ] [ Cancel ]

like image 36
Justin Ludwig Avatar answered Oct 18 '22 21:10

Justin Ludwig