检测浏览器或标签页关闭

2022-01-30 00:00:00 jquery javascript

是否有任何跨浏览器 JavaScript/jQuery 代码来检测浏览器或浏览器选项卡是否正在关闭,但不是由于单击了链接?

Is there any cross-browser JavaScript/jQuery code to detect if the browser or a browser tab is being closed, but not due to a link being clicked?

推荐答案

如果我理解正确,您想知道选项卡/窗口何时有效关闭.好吧,AFAIK 在 Javascript 中检测这种东西的唯一方法是 onunload &onbeforeunload 事件.

If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in Javascript to detect that kind of stuffs are onunload & onbeforeunload events.

不幸的是(或幸运的是?),当您通过 link 或浏览器的后退按钮离开网站时,也会触发这些事件.所以这是我能给出的最好答案,我认为你不能在Javascript中原生检测到纯 close .如果我在这里错了,请纠正我.

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

相关文章