Explain Codes LogoExplain Codes Logo

Detect browser or tab closing

javascript
event-handling
browser-detection
session-storage
Anton ShumikhinbyAnton Shumikhin·Oct 25, 2024
TLDR

Detect a tab close with the beforeunload event. Attach it to window to trigger actions before the browsing session ends:

window.onbeforeunload = function(e) { // Code here, such as save protocol and confirmation messages e.returnValue = 'You have unsaved changes! Are you sure you want to exit?'; // Custom message might not always be displayed return e.returnValue; // Because some browsers get moody without it };

Use this for the 11th-hour data saves or exit confirmations, but remember that browsers might display a default text instead.

The cross-browser challenge

How to handle browser differences

Even though the beforeunload event is widely supported, it meets unique interpretations in different browsers. Browsers may swap the returned string with a generic warning to users, mostly to prevent pop-up spam.

Additional closure handling with unload

While the unload event can be used for additional clean-ups, it's not as reliable as beforeunload. It might not fire in some cases like those pesky browser crashes or when the browser is closed forcibly:

window.onunload = function() { // More cleanup code here };

Use it with caution since it's being phased out in modern web development.

Nifty trick: event.clientY

For the nostalgic support of legacy versions like IE7, checking the event.clientY property could save your day when detecting if the close button was clicked:

window.onbeforeunload = function(event) { if (event.clientY < 0) { // User clicked the close button - they really want out! } };

Just be sure to use this trick only when absolutely necessary.

Storing data until the fat lady sings

How to handle temporary data with sessionStorage

Use sessionStorage to store data while the page is live, but auto-clears when the tab is closed:

// Save data to sessionStorage sessionStorage.setItem('key', 'value'); // Retrieve data when you need it later const value = sessionStorage.getItem('key'); // Clean up just in case MI6 is watching sessionStorage.removeItem('key');

This validates sessionStorage to be efficient for data handling during page unloading.

jQuery and sessionStorage are the best of friends

sessionStorage can be manipulated using jQuery for cleaner code and more straightforward maintenance:

// Setting an item with jQuery $(window).on('beforeunload', function() { $.sessionStorage.setItem('key', 'value'); }); // Retrieving and taking out the trash (removing items) $(document).ready(function() { var value = $.sessionStorage.getItem('key'); $.sessionStorage.removeItem('key'); });

Remember, jQuery can offer a more streamlined syntax and additional cross-browser insurance.

Potential issues and their workarounds

Redirecting for sanitization

In certain edge cases, or with browsers that should have been retired like IE7, it could be necessary to redirect the user to a logout page on closure to invalidate user sessions or perform any server-side cleanup. Make sure this doesn't disrupt any data-saving operations on beforeunload:

window.onbeforeunload = function() { // Redirect to a logout page, because order policies aren't just for restaurants window.location.href = '/logout'; };

Final thoughts on detection

At present, the closest we can get to detecting browser tab/window closing events in JavaScript is through the onbeforeunload and onunload events. However, always keep an eye out for new APIs to be sure you're up to date with the web's constant evolution.

A deeper dive into beforeunload

The beforeunload event is the opportunity to confirm navigation away from the webpage and alerting of unsaved changes. On the flip side, browsers may not always display a custom message due to variations in their implementations.

Confirming the close action

Unfortunately, we can't directly detect the user's decision to leave due to privacy reasons. But, you can still run cleanup actions, or analytics logging in this event.

The persistence challenge

Always consider how long you want your data to stay stored. Use sessionStorage for data that should only persist while the tab is open, and localStorage for long-term data storage.