javascript / jquery-用户关闭浏览器时的跨浏览器检测?

javascript / jquery-用户关闭浏览器时的跨浏览器检测?

问题描述:

我正在寻找一种可靠的方法来检测用户何时关闭浏览器/选项卡以显示警告消息(我正在使用使用会话的购物车)。

i'm looking for a reliable way on how to detect when a user closes the browser/tab in order to display a warning message (i'm having a shopping cart which uses sessions).

我已经搜索过并且找不到合适的解决方案-每次刷新页面时window.onunload都会显示一条消息..

i've googled and couldn't find a proper solution - window.onunload will display a message every time i'm refreshing the page ..

有什么想法吗?
谢谢

any ideas? thanks

您无法分辨关闭,重新加载,后退/前进等之间的区别。

You can't tell the difference between closing, reloading, back/forward etc.

beforeunload 被触发。

取决于如果您自己启动了窗口,则可以在调用 window.close()之前运行代码,但是如果用户自己关闭窗口,则不会调用该代码。

Depending on if you launched the window yourself, you could run your code before calling window.close(), but this won't be called if the user closes the window themselves.