There are a few ways to detect browser or tab closing in JavaScript, but the most common way is to use the ‘onbeforeunload’ event.

The ‘onbeforeunload’ event is triggered before the page is unloaded, and it allows you to display a dialog box asking the user if they want to leave the page.

Here is an example of how you can use the ‘onbeforeunload’ event to detect browser or tab closing:

window.onbeforeunload = function() {
    return "Are you sure you want to leave?";
}

This will show a dialog box with the message “Are you sure you want to leave?” when the user tries to close the browser or tab.

You can also customize the dialog box by returning an object with a specific property set.

window.onbeforeunload = function (e) {
    e.returnValue = "Are you sure you want to leave?";
    return "Are you sure you want to leave?";
}

It’s important to note that since this is a security feature, modern browsers will not allow you to run any code on beforeunload event. So you can’t execute any logic just before the browser is closed.

Also, the ‘onbeforeunload’ event will not be triggered when you refresh the page, so you can’t use it to detect page refreshes.

Another way to detect browser or tab closing is to use a ‘WebSocket’ connection and close it when the browser is closed, but it has some limitations and it’s not recommended.

Also Read:

Categorized in: