Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Browser close in JavaScript?

Tags:

javascript

Is there a way to trap the browser closing event from JavaScript? I don't want to do this in Page Unload event or anything. It must be handled on clicking the browser close button.

Is it possible?

like image 460
RameshVel Avatar asked Jul 17 '09 13:07

RameshVel


3 Answers

No. You only have onbeforeunload event, available as raw javascript (jquery doesn't include this event).

If you want to try it, try to post here an answer and, without pressing "post your answer" try to close the browser window.

This is the closest way to access the "close window" event.

like image 62
Ionuț Staicu Avatar answered Sep 30 '22 16:09

Ionuț Staicu


onbeforeunload event captures every unload event but there is some trick way to handle if user closing browser by clicking close button, here is a sample code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function(){

    //handle if your mouse is over the document body,
    //if not your mouse is outside the document and if you click close button return message or do what you want

    var out = false;
    $("body").mouseover(function(){
      out=false;
    }).mouseout(function(){
      out=true;
    });


    $(window).bind('beforeunload', function(e){
    if(out)
        {return "Do you really want to leave this page now?"}
    });

  });
  </script>

</head>
<body>
  <p>   
    <a href="http://cssbased.com">go outside</a>
    <br>
    <a href="test.html">reload page</a>
    <span> </span>
  </p>
</body>
</html>
like image 40
mkavici Avatar answered Sep 30 '22 16:09

mkavici


Here is nice article about this from 4guysfromrolla

    <script language="JavaScript">
        window.onbeforeunload = confirmExit;
        function confirmExit()
        {
            return message to display in dialog box;
        }
    </script>
like image 35
Marselus Chia Avatar answered Sep 30 '22 15:09

Marselus Chia