Makizh
Makizh

Reputation: 189

How to detect browser tab close event in javascript

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>

Upvotes: 3

Views: 17653

Answers (4)

JUGAL HALVADIYA
JUGAL HALVADIYA

Reputation: 19

Try This its work i tested it in my project

let pageClose=false;
         window.addEventListener('beforeunload', function (event) {
            pageClose=true;

            setTimeout(function(){
                pageClose=false;
                console.log(pageClose);
            },1000);
        });
        
        setTimeout(function(){
            pageClose=false;
            console.log(pageClose);
        },1000);
        
        document.addEventListener('visibilitychange', function (event) {
            console.log(pageClose);
            if(document.visibilityState == 'hidden') {
                if(pageClose){
                    //add your code on browser or tab close 
                }
            }
        }); 

Upvotes: 0

Valentin PKStore
Valentin PKStore

Reputation: 87

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.

Upvotes: 1

Not the best answer
Not the best answer

Reputation: 301

In some browsers, calls to window.alert(), window.confirm(), and window.prompt() may be ignored during this event. See the HTML specification for more details.

https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

Try a console.log and check "Preserve Log" in your Console. You will see that it's just alert() that doesn't work in your case

Upvotes: 2

Hamms
Hamms

Reputation: 5107

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.

Upvotes: 1

Related Questions