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 want to do some stuff when user is leaving a page, I add this code

window.onbeforunload = function (e){
   return "You save some unsaved data, Do you want to leave?";
}  

This prompt can notify the user and user can stay on the page or leave. But I want more to know whether he leaves or not, and do thing on his decision. I tried this,

window.onbeforunload = function (e){
   var event = jQuery.Event(e);
   var result = confirm('want to leave?');
   if (result ==  false){
     //do sth.. 
     event.preventDefault();
   }else{
    //do clean up
   }
} 

But it fails!! It always goes away!

Can any body help me doing this?

See Question&Answers more detail:os

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

1 Answer

The method you use (preventing bubbling of the event) is intentionally not possible, otherwise you could prevent users from leaving your page.

You can achieve something similar to what you want by doing your cleanup onunload, and do the stuff you always want to do onbeforeunload.


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