To clear the session when the user leaves your site, you can use the beforeunload event in JavaScript. This event is triggered just before the user navigates away from the current page, allowing you to perform cleanup tasks, such as clearing the session, before the page unloads.

Here's how you can do it:

// Function to clear the session data function clearSession() { // Perform the necessary actions to clear the session // For example, you can use localStorage or sessionStorage to store session data // Clearing the session might involve removing or resetting the stored session data // For example, if you are using sessionStorage: // sessionStorage.clear(); } // Event listener to trigger the clearSession function when the user leaves the site window.addEventListener('beforeunload', function () { clearSession(); });

In this code, we define a clearSession function that performs the necessary actions to clear the session data. The exact implementation of this function depends on how you store your session data. For example, if you are using localStorage or sessionStorage, you can clear the session by calling localStorage.clear() or sessionStorage.clear().

Next, we add an event listener to the window object for the beforeunload event. When the user leaves the site or navigates away from the page, the beforeunload event is triggered, and the clearSession function will be called, allowing you to clear the session before the page unloads.

Please note that the beforeunload event is a critical event, and browsers restrict what you can do in its handler to prevent abuse. You can show a confirmation dialog to the user to prompt them whether they want to leave the page or not, but you cannot customize the dialog's message to trick the user into staying on the page. The purpose of the beforeunload event is to allow you to perform necessary cleanup tasks, not to interfere with the user's choice to leave the site.

Have questions or queries?
Get in Touch