onbeforeunload confirmation screen customization

Nyla Pareska picture Nyla Pareska · Aug 26, 2009 · Viewed 13.2k times · Source

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.

Answer

Eli Grey picture Eli Grey · Aug 26, 2009
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.