8

I am using the following code snippet to trigger an alert before page closes but Chrome seems to ignore the message and displays its default message "Do you want to leave this site? Changes you made might not be saved". How can I make chrome show my message instead of the default one?

window.onbeforeunload = function(e) {
    e.returnValue = "A search is in progress, do you really want to stop the search and close the tab?";
    return "A search is in progress, do you really want to stop the search and close the tab?";
}
Cashif Ilyas
  • 1,619
  • 2
  • 14
  • 22

2 Answers2

2

I only recently realized that Chrome had changed the behavior of onbeforeunload. I found a workaround that works for the main browsers (tested in Chrome, Firefox and IE, the jsFiddle for some reason doesn't work in Firefox, but my website does). Using jQuery UI, you can make a dialog window come up when leaving the page that gives more info about why leaving the current page would be a problem.

window.onbeforeunload = function (e) {
    $('<div title="Warning!">A search is in progress, do you really want to stop the search and close the tab? If not, choose "Stay on page" on the browser alert.</div>').dialog({
        modal:true,
        close: function(){$(this).dialog('destroy').remove();}
    });
    return "Random message to trigger the browser's native alert.";
}

jsFiddle here

Mar
  • 112
  • 1
  • 13
0

Update: Deprecated in Chrome : https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en

Try the following:

window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'A search is in progress, do you really want to stop the search and close the tab?';
    }

    // For Safari
    return 'A search is in progress, do you really want to stop the search and close the tab?';
};

Message I get in Chrome (both custom and default):

A search is in progress, do you really want to stop the search and close the tab?

Are you sure you want to leave this page?

Source jsFiddle

Kairat
  • 790
  • 3
  • 7