Explain Codes LogoExplain Codes Logo

Confirmation before closing of tab/browser

javascript
event-listeners
browser-compatibility
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 2, 2025
TLDR

Preserve the sanity of your users' unsaved edits with this quick fix. Just inject a listener for the beforeunload event to your window object, and assign a custom message to the returnValue property of the event. This prompts most browsers with a confirmation dialog. Dead simple, like Batman swooping in to save the day.

window.onbeforeunload = function(e) { e.returnValue = 'Wait! Did you save your changes?'; return e.returnValue; // Ensuring old browsers don't feel left out. };

Maximize inter-browser compatibility

Adopting event listeners

For modern browsers, swap window.onbeforeunload with window.addEventListener('beforeunload', eventHandlerFunction). It's a bit like losing a baby tooth, and finding a shiny coin from the tooth fairy.

window.addEventListener('beforeunload', function (e) { e.preventDefault(); // Don't you dare close this tab! e.returnValue = ''; // Chrome demands a tribute. return 'You sure you don't want to stick around a bit longer?'; // Adding sweetness to the bitterness. });

Safari, that peculiar kid, prefers you to simply return your string. Chrome, the popular guy, might block your dialog if the user hadn't interacted with the page.

Aesthetic and functional enhancement

Surely you wouldn't want an overenthusiastic friend pestering you: trigger beforeunload only when required. This is like offering a blanket only when it's cold, and not in the middle of a summer day.

let isDirty = false; // Innocent until proven guilty! window.addEventListener('beforeunload', function (e) { if (!isDirty) { return undefined; // No guilt, no problem. } e.preventDefault(); e.returnValue = ''; // Chrome gets its due. return 'Unsaved changes? Better not leave!'; // The moral compass. });

Adding a touch of personality

Personalize dialog text and regulate display frequency for a standout UX. Keep in mind that quasi-smart browsers are fond of their default messages, and might not display your custom text.

Manage user controls and exceptions

Allowing safe passage (when needed)

Some actions such as logouts or form submissions should probably proceed without pestering confirmations. Treat them like VIP guests, not rushing them with your confirmation protocols.

function optOut() { window.removeEventListener('beforeunload', byeFelicia); // Part ways gracefully. // execute your navigation action here } function byeFelicia(e) { e.preventDefault(); e.returnValue = ''; return 'Seriously? Leaving so soon?'; // A final attempt to make them stay. } window.addEventListener('beforeunload', byeFelicia);

Predicting potential possessiveness

Not all browsers react equally to beforeunload; remember that programmers have preferences too. IE prefers e.cancelBubble = true, others expect e.stopPropagation(). Be prepared to handle such quirks or outright inconsistencies.