published: 22 May 2022
2 min read
How to detect browser or tab closing in JavaScript
In JavaScript, you can use the beforeunload
event to detect a tab or window closing in a browser. It is used to alert the user about unsaved changes on the webpage or to prevent the user from mistakenly closing the window or the browser.
Here is an example that you can use to display an alert message when the user tries to close a tab or window:
window.addEventListener('beforeunload', (e) => {
e.preventDefault()
return (e.returnValue = 'Are you sure you want to close?')
})
We use the addEventListener()
method to attach an event handler to any DOM object including HTML elements, document
object, and window
object.
The beforeunload
is fired right before the window, the document, and its resources are about to be unloaded. At this point, the document is still visible, and the event is still cancelable.
According to the specification, you must call preventDefault()
on the event to show the confirmation dialog. The preventDefault()
method is used to prevent default action of an event. In this case, the unloading of resources, the window, and the document.
Note that some browsers may not display prompts created in beforeunload
event handlers unless the user has interacted with the page. This is used to combat unwanted pop-ups created by malicious websites.
Are we missing something? Help us improve this article. Reach out to us.
How to detect browser or tab closing in JavaScript
In JavaScript, you can use the beforeunload
event to detect a tab or window closing in a browser. It is used to alert the user about unsaved changes on the webpage or to prevent the user from mistakenly closing the window or the browser.
Here is an example that you can use to display an alert message when the user tries to close a tab or window:
window.addEventListener('beforeunload', (e) => {
e.preventDefault()
return (e.returnValue = 'Are you sure you want to close?')
})
We use the addEventListener()
method to attach an event handler to any DOM object including HTML elements, document
object, and window
object.
The beforeunload
is fired right before the window, the document, and its resources are about to be unloaded. At this point, the document is still visible, and the event is still cancelable.
According to the specification, you must call preventDefault()
on the event to show the confirmation dialog. The preventDefault()
method is used to prevent default action of an event. In this case, the unloading of resources, the window, and the document.
Note that some browsers may not display prompts created in beforeunload
event handlers unless the user has interacted with the page. This is used to combat unwanted pop-ups created by malicious websites.
Are you looking for other code tips?
JS Nooby
Javascript connoisseur