Detect When Tab Is Being Closed And Show Confirmation Dialog With JavaScript
September 25, 2020 by Andreas Wik
Some websites/apps shows a warning dialog when you’re about to close the tab/window. For example, maybe you’re writing a draft email that hasn’t been saved to the server yet, and suddenly you decide to close the tab. Then the browser may present you with a confirmation dialog, saying something like “Leave site? Changes you made may not be saved.”
This can be achieved with JavaScript by simply adding an event handler for the onbeforeunload window event.
Like so:
window.onbeforeunload = function(e) {
return true;
}
Or with ES6:
window.onbeforeunload = () => true;
Check out the demo.
Worth noting is that some browsers require that there is some interaction with the page, like typing into an input field, in order for the event handler to trigger.
Fun but sad fact: A few years ago you could actually return a string which would then be used as message in the dialog instead of the browser’s default one. This was unfortunately used extensively by scammers, so browser vendors removed support for it.
Well, that’s it.
Take care out there!