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

javascript - Difference between onbeforeunload and onunload

What are the differences between onbeforeunload and onunload ? Also I have a specific question related to it's use on the iPad...I have a page (myPage.html) where I am trying to show an alert when the page is closed (i.e. X is pressed to close the tab on iPad)

Now I tried using both window.onunload and window.onbeforeunload Below are my findings on the iPad;

  1. Using window.onunload , I am able to get an alert when user navigates to a different page from myPage.html (either by clicking on some link or doing a Google search while on myPage.html) . However nothing happens when the tab is closed from the minimized view (X)

  2. Using window.onbeforeunload, I neither get an alert even if the user navigates to a different page from myPage.html OR if he closes the tab (X) from the minimized view.

I wanted to know if there is any alternate way to fix this issue ?

Thank you.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

onunload is responsible for executing an instruction when the page is closed. It also causes issue with IE and AJAX.

onbeforeunload is more efficient because it does not run in competition with the actual closing of the window and is triggered before onunload

I know Opera used to not acknowledge onbeforeunload - not sure if they've fixed that, but I always register the listener for both to be safe:

window.onunload = window.onbeforeunload = (function(){...

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

...