How to detect browser tab close event in javascript

Viewed 9723

Tried to call browser tab close event when click on close tab icon in chrome browser but not working.I want to show alert message before close the browser tab.How do it?

Below code is not working:

<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<script type="text/javascript">
    window.onbeforeunload = function(evt) {
        var message = "Are you sure?"; 
        /* InternetExplorer/Firefox*/
        var e = evt || window.event
        e.returnValue = message 
        /* WebKit browser */
        return message;
    }
</script>

<body>
 
    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p> 

</body> 
</html>
3 Answers

You are in fact correctly detecting the tab close event! The problem is with your triggered action. From the relevant MDN documentation:

To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all.

This means that it's going to be very difficult for you to show an alert message before closing the browser tab as you say you want do you. You can however achieve something similar by using the return value on the handler. Again quoting from the documentation:

When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string.

See this other question Warn user before leaving web page with unsaved changes for more details.

To prevent Scam, Browsers are cautios with those messages. Most are very limited in what you can do. Chrome shows the standardized message "Leave Site? Changes that you made may not be saved." which is not changable afaik. To achieve this, simply use:

  window.onbeforeunload = function () {
        return true;
    };

An alternative to that is to detect when the mouse is leaving the window. That is not the same, but often leaving the viewport is the action taken before closing a tab. You can detect the event when the mouse leaves the window and trigger whatever message or pop up you like. I personally find that very annoying though.

Related