Confirmation before closing of tab/browser
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.
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.
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.
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.
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.
Was this article helpful?