Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wrote a code for onbeforeunload. It works for IE but not for any other browser.

var unloadFunction = function(){return "";}
window.addEventListener('beforeunload', unloadFunction); 

What can possibly go wrong with this code. :( I am not able to understand. I want this to work in all browsers in order to show a confirm popup to the user before one exist the page.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
382 views
Welcome To Ask or Share your Answers For Others

1 Answer

Before unload processing has been modified since it was introduced due to badly behaved web pages. In result, browsers may or may not suppress alerts during unload event processing.

Refer to MDN for detailed information, but note the returnValue mentioned is a property of the event object, not a value returned from the event handler function.

The example below runs in major browsers and IE (for windows 10 at least).

  • Firefox and IE reported the message provided in event.returnValue.
  • Chrome ignored the message and simply asked

    Leave site?
    Changes that you made may not be saved.

  • Only IE showed the alert box.

var unloadFunction = function( event){
    event.returnValue = "do you really want to leave this page";
    alert("unloading");
};
window.addEventListener('beforeunload', unloadFunction); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...