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

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

javascript - catching beforeunload confirmation canceled?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...