Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...