JavaScript +卸载前
我对我的申请有疑问。每当用户意外关闭浏览器窗口时,我想在此之前执行一些清理操作。我已经使用了 onunload 事件,但问题是该事件有时会触发,有时不会。我该怎么办,有没有更好的方法来处理此类问题。
I have a query regarding my application. Whenever user closes browser window accidentally I'd want to do some clean up operations before that. I have used onunload event but problem is this event is sometimes is firing and sometimes doesn't. What should I do, is there better way to handle such type of problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请参阅有关 onbeforeunload 的 MSDN 文章
另外还有类似问题 在SO中
See the MSDN article on onbeforeunload
Also there is a similar question in SO
尝试:
Try:
根据我的经验,onunload 在不同浏览器中的工作方式有所不同。为什么不使用另一个名为 onbeforeunload 的事件处理程序呢?它应该有效。 Onbeforeunload 将在窗口关闭之前首先执行,因此应该可以解决您的问题。
From my experience onunload works differently in different browsers. Why dont you use another event handler called onbeforeunload instead. It should work. Onbeforeunload will execute first before the window closes, so that should solve your problem.
这是有效的:
例如,如果您正在使用 SharedWorkers 并且您需要告诉工作人员需要管理的端口少了,这会很方便 - 否则,您最终可能会刷新一个浏览器选项卡并得到类似“成功”的信息连接到:10 个其他选项卡”,因为一个选项卡使工作线程保持活动状态,而另一个选项卡的刷新则不断将新的端口连接推送到您的阵列。
希望这可以帮助。
This works:
This is handy if, for instance you're working with SharedWorkers and you need to tell the worker that there is one less port to manage -- otherwise, you could end up refreshing one browser tab and get something like a "Successfully connected with: 10 other tabs" because the one tab is keeping the worker alive while the other tab's refreshes keep pushing new port connections to you array.
Hope this helps.
出于安全原因,这是不允许的。 onbeforeunload 是一个浏览器 API,在不同的浏览器上有不同的行为。
This is not allowed because of security reasons. onbeforeunload is an browser API that have different behaviors on different Browsers.
这是我的答案之一,仅当用户想要关闭窗口并在某种程度上劫持浏览器消息时才给你 onbeforeunload.....
我认为它可能对任何人都有用,谢谢......
this is one of my answer that gives u the onbeforeunload only if the user want to close the window and also to hijack the browser message for some extent.....
i think it might be useful for any body thanks.....