onbeforeunload 和 onunload 之间的区别
onbeforeunload 和 onunload 之间有什么区别? 另外,我有一个与其在 iPad 上使用相关的具体问题...我有一个页面 (myPage.html),我试图在页面关闭时显示警报(即按下 X 来关闭 iPad 上的选项卡)
现在我尝试同时使用 window.onunload 和 window.onbeforeunload 以下是我在 iPad 上的发现;
使用 window.onunload ,当用户导航到与 myPage.html 不同的页面时(通过单击某个链接或在 myPage.html 上进行 Google 搜索),我能够收到警报。但是,当从最小化视图 (X) 关闭选项卡时,没有任何反应
使用 window.onbeforeunload,即使用户从 myPage.html 导航到不同的页面或者关闭选项卡 (X),我也不会收到警报 。
我想知道是否有其他方法可以解决这个问题?
谢谢。
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;
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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
onunload
负责在页面关闭时执行一条指令。它还会导致 IE 和 AJAX 出现问题。onbeforeunload
效率更高,因为它不会与窗口的实际关闭竞争,而是在onunload
之前触发。我知道 Opera 过去不承认
onbeforeunload
code> - 不确定他们是否已经解决了这个问题,但我总是注册监听器以确保安全: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 beforeonunload
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:添加 AlienWebguy 的 ans,以避免在支持这两个事件的浏览器上进行双重调用,
Adding with AlienWebguy's ans, to avoid dual calls at the browsers that support both events,
onbeforeunload
:event.preventDefault();
取消关闭页面onunload
:我能想到的唯一原因是您想要使用onunload 结束
onbeforeunload
是您的onunload
代码可能需要花费大量时间的地方,并且不希望用户看到关闭时挂起的窗口。onbeforeunload
:event.preventDefault();
onunload
:The only reason I can think of why you would want to use
onunload
overonbeforeunload
would be where youronunload
code could take some significant time, and don't want the user to see a window that hangs while closing.onbeforeunload
和onunload
之间的一个显着区别(除了可取消性之外)是前者针对下载链接而触发,而后者则不会。示例:download
将触发onbeforeunload
处理程序,但不会触发onunload
。One significant difference (other than cancelability) between the
onbeforeunload
andonunload
is that the former is triggered for download links and the latter is not. Example:<a href="https://somewhere.com/thething.zip">download</a>
will trigger theonbeforeunload
handler, but not theonunload
.