Home >Web Front-end >JS Tutorial >How to Distinguish Between a Browser Refresh and a Window Close?
Distinguishing Between Refresh and Close Browser Actions
Determining the distinction between refreshing a page and closing a browser can seem challenging, as both actions trigger the ONUNLOAD event. However, there is a solution to this conundrum.
Solution:
This approach leverages HTML5 local storage and server-client communication:
ONUNLOAD Handler: On the page, add an on-unload handler to the window using pseudo-JavaScript:
<code class="javascript">function myUnload(event) { if (window.localStorage) { window.localStorage['myUnloadEventFlag'] = new Date().getTime(); } askServerToDisconnectUserInAFewSeconds(); // Synchronous AJAX call }</code>
This function:
ONLOAD Handler: On the body, add an on-load handler:
<code class="javascript">function myLoad(event) { if (window.localStorage) { var t0 = Number(window.localStorage['myUnloadEventFlag']); if (isNaN(t0)) t0 = 0; var t1 = new Date().getTime(); var duration = t1 - t0; if (duration < 10 * 1000) { // Browser reload askServerToCancelDisconnectionRequest(); // Asynchronous AJAX call } else { // Tab/window close // Perform desired actions (e.g., do nothing) } } }</code>
This function:
This solution works for differentiating between tab/window closures, reload actions, followed links, and submitted forms. It is applicable in browsers with HTML5 local storage support. Note, however, that it relies on the unload event and may not be compatible with older browsers like MSIE7.
The above is the detailed content of How to Distinguish Between a Browser Refresh and a Window Close?. For more information, please follow other related articles on the PHP Chinese website!