Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

beforeunload on IE 11 - do not prompt user does not work

When adding a listener to the global window object for the beforeunload event, IE 11 (and 10) does not behave as Chrome and Firefox.

Normally, you return a string that will be used to populate the browser-native dialog prompt or you return an empty string if you do not want the dialog to prompt the user.

However, in IE 11, if you return an empty string and/or set the evt.returnValue to an empty string, the browser-native 'Navigate Away' dialog is opened and prompts the user to acknowledge that they may lose unsaved changes.

Is there any way (without having to remove the event listener) to have the dialog not appear in IE 11?

See my JSFiddle (in IE - as this should work properly in Chrome, Firefox, and Safari).

Here's the source in the fiddle:

var isDirty = false;
var message = '** You have unsaved changes. **'
window.addEventListener('beforeunload', function(evt){
  if(isDirty) {
    evt.returnValue = message;
    return message;
  }
  delete  evt.returnValue;
  return "";
});
like image 376
freddy mercury Avatar asked Dec 05 '15 21:12

freddy mercury


People also ask

Is beforeunload deprecated?

Deprecated. Not for use in new websites.

What is onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


1 Answers

The solution is not to return anything (which is the same as return; or return undefined;).

var isDirty = false;
var message = '** You have unsaved changes. **'
window.addEventListener('beforeunload', function(evt){
  if(isDirty) {
    evt.returnValue = message;
    return message;
  }
  delete evt.returnValue;
});
like image 59
freddy mercury Avatar answered Oct 15 '22 16:10

freddy mercury