问题
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).
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
回答1:
You can't tell the difference between closing, reloading, back/forward etc.
beforeunload is fired on all of them.
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.
回答2:
I don't believe such a thing is possible. The browser can fire an event when the page (un)loads, but who's to say wether the user is navigating, or closing the browser/tab?
来源:https://stackoverflow.com/questions/6107967/javascript-jquery-crossbrowser-detection-when-user-is-closing-the-browser