Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect browser tab close event in javascript

Tags:

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>
like image 364
Makizh Avatar asked Dec 05 '25 14:12

Makizh


2 Answers

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

like image 80
Not the best answer Avatar answered Dec 08 '25 06:12

Not the best answer


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.

like image 43
Hamms Avatar answered Dec 08 '25 06:12

Hamms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!