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
351 views
in Technique[技术] by (71.8m points)

javascript - Event calling before page unload

I want to pop up a dialog before an html page is unloaded asking to unload page or not. If yes is selected then the unload continues, and if no is selected then the unload event is canceled.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can't set the text to "yes"/"no" (it'll be "Ok"/"Cancel" in most browsers), but you can prompt (be careful when using this) when leaving the page in any manner using window.onbeforeunload, like this:

window.onbeforeunload = function() {
  return "Are you sure you wish to leave the page?";
}

Only use this if you have a good reason, don't annoy your users. That being said, this will prompt when leaving the page, that includes history back, forward, refresh, closing the window/tab, clicking a link to navigate away or submitting a form, etc. So you'll probably want to call this when going somewhere that shouldn't prompt:

window.onbeforeunload = null;

For example, submitting a form of information, you'd want to prompt when leaving/losing the data, but not when actually submitting it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

56.9k users

...