Search code examples
javascriptbrowsercross-browseronbeforeunload

Detect browser close event


I want to capture the browser window/tab close event. I have tried the following But not working:

<script type="text/javascript">
window.onbeforeunload = function(){ myUnloadEvent(); }
function myUnloadEvent() {
    alert ('Calling some alert messages here');
}
</script>
<body>
Body of the page goes here.
</body>

Tried these links also but no more success.

javascript to check when the browser window is close
How to capture the browser window close event?
javascript detect browser close tab/close browser
Trying to detect browser close event

Problem :

I just want to detect the browser close event and do some handling on that without showing the prompt to the user.

I have tried many methods to detect browser close event through jQuery or JavaScript. But unfortunately I could not succeed. The onbeforeunload and onunload methods are also not working.

Any help will be highly appreciated. Thanks


Solution

  • You cannot show an alert() on an onbeforeunload. You need to return to show a confirm dialog.

    <script type="text/javascript">
    window.onbeforeunload = function(e){  
      return 'Calling some alert messages here'; //return not alert
    }
    </script>
    <body>
    Body of the page goes here.
    </body>
    

    Also do not call a function like that, write directly in the onbeforeunloadOR return myUnloadEvent(); It depends what you are trying to do inside onbeforeunload. Try not to make any AJAX call as the browser may not run the script. You can unset web storage varibles, delete session, etc.

    Also beware that this event will also fire when you refresh the page.