JavaScript 中如何区分重新加载和关闭?
所以我遇到的情况是用户可以重新加载或关闭浏览器选项卡。在这两种情况下,我希望脚本采取不同的操作。有没有办法区分重新加载(生成 onUnload 和 onLoad 事件)和用户关闭选项卡(生成 onUnload 事件)?
So I have a situation where a user can do a reload or close the browser tab. In both situations I want the script to take different actions. Is there a way I can differentiate between a reload, which generates an onUnload followed by an onLoad event, and closing of the tab by user (which generates an onUnload event)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
id' 建议在
onUnload
触发时在浏览器中存储一些值,以便您可以在onLoad
处理程序中检查该值。有关在浏览器中存储数据的信息,请参阅此问题
,另外,您可能会保存一些时间戳检查 onUnload 和 onLoad 之间经过了多少时间,确保它实际上是“重新加载”。
id' recommend storing some value the browser when
onUnload
fires, so you can check for this value in theonLoad
handler.see this question for info on storing data in the browser
additionally, you might save some timestamp to check how much time has elapsed between onUnload and onLoad, making sure it's actually a 'reload'.