Built-in function:
window.onbeforeunload = function(evt) {
or through an event listener (recommended):
window.addEventListener("beforeunload", function(evt) {
or if you have jQuery:
$(window).on("beforeunload", function(evt) {
Notes:
When this event returns a non-empty value, the user is prompted to confirm the page is unloaded. In most browsers, the event return value is displayed in this dialog.
As of May 25, 2011, the HTML5 specification states that calls to window.showModalDialog (), window.alert (), window.confirm (), and window.prompt () can be ignored during this event.
See the documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
source share