Open In App
Related Articles

How to detect browser or tab closing in JavaScript ?

Improve Article
Save Article
Like Article

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser. 

The addEventListener() method is used to set up a function whenever a certain event occurs. The beforeunload event is fired just before the windows and its resources are to be unloaded. When this event is fired, the webpage is visible and the event is still cancellable at this point. 

The event handler should call preventDefault() to show the confirmation dialog according to the specifications. If the user wishes to continue to a new page, then it navigates to the new page, otherwise, the navigation is canceled. However, older browsers may not support this method and a legacy method is used in which the event handler must return a string. This returned string can be empty. 

Some browsers may not decide to show any confirmation boxes unless the user has interacted with the page. This is used to prevent unwanted or malicious websites from creating unnecessary pop-ups. The user may have to interact with the page to see the confirmation message. This method works for detecting both when a tab is being closed or when the browser is being closed. 


window.addEventListener('beforeunload', function (e) {
    e.returnValue = '';



<!DOCTYPE html>
        How to detect browser or tab closing
    <h1 style="color: green">
    <b>Detect browser or tab closing</b>
        The beforeunload function is triggered
        just before the browser or tab is to be
        closed or the page is to be reloaded.
        Modern browsers require some interaction
        with the page, otherwise the dialog box
        is not shown.
        <textarea placeholder = "Trigger an
        interaction by writing something here">
                <script type="text/javascript">
        window.addEventListener('beforeunload', function (e) {
            e.returnValue = '';


Detect browser or tab closing

Detect browser or tab closing

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

Last Updated : 11 Nov, 2022
Like Article
Save Article
Similar Reads
Related Tutorials