JavaScript

How to detect browser or tab closing in JavaScript

In this tutorial, we are going to see how to detect browser or tab closing in JavaScript.

We can detect a tab or window using the beforeunload event. This can be used to alert the user if some data is not saved on the page or if the user has mistakenly strayed from the current page by closing the tab or browser.

The addEventListener() method is used to configure a function whenever an event occurs. The beforeunload event is triggered just before a browser window/tab is closed.

Some browsers may choose not to display the confirmation box unless the user has interacted with the page.
 

Script to detect browser or tab closing in JavaScript :
<script type="text/javascript"> 
    window.addEventListener('beforeunload', function (e) { 
        e.preventDefault(); 
        e.returnValue = ''; 
    }); 
</script>
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “How to detect browser or tab closing in JavaScript

  • Gabriel

    It doesn’t work. It includes reload or navigation actions.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *