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 "";
});
Deprecated. Not for use in new websites.
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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With