detect tab window closing in javascript

How to Detect Tab/Browser Closing in JavaScript

Sometimes you may want to prevent users from closing their browser tabs or window in order to complete the present task. For example, you may want to prevent users from closing tab/browser once they have made a payment so that you can direct them to another page. In this article, we will learn how to detect tab/browser closing in JavaScript.

How to Detect Tab/Browser Closing in JavaScript

You can detect tab/browser closing beforeunload event that is automatically triggered when a user tries to close tab/browser. This event is called just before window is closed, when it is still visible, and the navigation can be cancelled.

We will add an event handler for this event. You can show a confirmation box or warning message when this event is fired. It will allow users to cancel tab/window closure. On confirmation, user will be taken to new page, else navigation is cancelled.

Here is a simple JavaScript code for the same.

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

Let us say you have the following HTML page.

<!DOCTYPE html>

		How to detect browser or tab closing

	<h1 >
		Hello World
	<b>Detect browser or tab closing</b>
	<script type="text/javascript">
		window.addEventListener('beforeunload', function (e) {
			e.returnValue = '';


The above defined event handler is triggered when even beforeunload is fired. We use preventDefault() function to prevent the tab/window from closing. Thereafter you can choose to show a warning message or confirmation box as per your requirement, and proceed based on user input.

In this article, we have shown how you can prevent tab/window from closing but use it only when you have to, for example, to stop users from leaving your website after they pay, until payment is completed & confirmed on your site. Preventing users from closing tab/window without genuine reason is a bad practice and must be avoided if possible.

Also read:

How to Include Another HTML in HTML file
How to Call Function When Page is Loaded in JavaScript
How to Match Exact String in JavaScript
How to Convert Columns into Rows in Pandas
How to Set/Unset Cookie With jQuery

Leave a Reply

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