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

浪尽此生 提交于 2019-12-12 08:23:10

问题


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 "";
});

回答1:


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;
});


来源:https://stackoverflow.com/questions/34110931/beforeunload-on-ie-11-do-not-prompt-user-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!