-1

My page has a form with many information that could be collected from the user. If the user tries to close this page, it should display a confirmation box saying: "are you sure you want to leave this page?".

$(window).on('beforeunload',function(e){
     //alert code
}

Everything is OK. But in firefox when I'm using the search bar, Firefox will ignore my alert and redirect to the search page.

Any suggestions?

dodopok
  • 868
  • 14
  • 22
Jonny Vu
  • 1,420
  • 2
  • 13
  • 32

2 Answers2

2

The beforeunload event is fired when the window, the document and its resources are about to be unloaded.

When a string is assigned to the returnValue Event property, a dialog box appears, asking the users for confirmation to leave the page. When no value is provided, the event is processed silently:

window.addEventListener("beforeunload", (event) => {
  event.returnValue = null;
});

// is equivalent to
window.addEventListener("beforeunload", (event) => {
  event.preventDefault();
});

WebKit-based browsers may not follow the spec for the dialog box. An almost cross-browser working example:

window.addEventListener("beforeunload", (event) => {
  const confirmationMessage = "your message";

  event.returnValue = confirmationMessage;
  return confirmationMessage;
});

NOTE When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog. In Firefox 4 and later the returned string is not displayed to the user. Instead, Firefox displays it's own predefined string.

Since 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.

Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.

Alex M
  • 2,756
  • 7
  • 29
  • 35
  • This is almost correct on firefox, which behaves differently than chrome. This answer worked for me. https://stackoverflow.com/a/64282126/8714371 – M.Nar May 26 '22 at 20:13
0

You can write code something like this

$(window).bind('beforeunload', function () {
    return 'Your custom message here';
});

You can not generate you custom popup in beforeunload method.

Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42