How to detect browser close and tab close event in JavaScript

There is a function called onbeforeunload in javaScript, which could help to detect browser close event as well as tab close event. With the help of this function you can alert any message while user is going to close tab or browser as you have seen this type of features on many website, when you leave the page, A popup alert shows with some message like “Do you really want to close?” etc.


Following javascript code you could use to detect browser close and tab close event.

window.onbeforeunload = function () {
    alert("Do you really want to close?");
};