Home >Web Front-end >JS Tutorial >How to Distinguish Between Browser Refresh and Closure Using HTML5 Local Storage?
Identifying Between Refresh and Close Browser Actions
Distinguishing between page refresh and browser closure can pose a challenge when both actions trigger the ONUNLOAD event. However, there is a solution using HTML5 local storage and client/server AJAX communication.
Onunload Event Handling
In your page's window, add an onunload event handler:
function myUnload(event) { // Set a local storage flag indicating an unload event if (window.localStorage) { window.localStorage['myUnloadEventFlag'] = new Date().getTime(); } // Notify the server of a disconnection request askServerToDisconnectUserInAFewSeconds(); // Synchronous AJAX call }
Onload Event Handling
In your page's body, add an onload event handler:
function myLoad(event) { if (window.localStorage) { // Check the time between the last unload event and the current time var t0 = Number(window.localStorage['myUnloadEventFlag']); var t1 = new Date().getTime(); var duration = t1 - t0; if (duration < 10 * 1000) { // Page reloaded: Cancel disconnection request askServerToCancelDisconnectionRequest(); // Asynchronous AJAX call } else { // Tab/window closed: Perform desired action } } }
Server-Side Management
On the server, implement a process to collect disconnection requests and schedule a timer thread to check for timed-out requests. Within 5 seconds (in this example), disconnect users with timed-out requests. If a disconnection cancellation is received, remove the corresponding request from the list.
This approach can also be used to differentiate between tab/window closing and link/form submissions. Place the event handlers on all pages with links or forms and their landing pages.
While this solution uses local storage, note that it may not be suitable for browsers that do not support HTML5 local storage. Consider specific approaches for handling these scenarios.
The above is the detailed content of How to Distinguish Between Browser Refresh and Closure Using HTML5 Local Storage?. For more information, please follow other related articles on the PHP Chinese website!