none
JavaScript Detect browser close IE 7

    Question

  • We have an application that logs into a system, we need to trap when a user may close the browser with the (X).  In IE6 we can do this succesfully with the following code

    In body tag

    onUnload = "handleBrowserClose();"

    function handleBrowserClose() {
      if (screenTop > 9999) {
         //handle logout event
       }
    }

    Unfortunetly since IE7 the screenTop now actually contains the actually value of the top position.  Does anyone have any suggestions on how to fix this in IE7 or a different way to trap that a user clicks the (X) button to close IE7?

    Saturday, December 09, 2006 1:35 PM

Answers

  • Here is on example with the onbeforeunload :

    1. main script (script.php) in which the "leaving" is watched (NB : this script had been opened through a existing window (with a "_blank" target in the form) :

    ....

    <script type='text/javascript'>
    window.onbeforeunload = function() {
       //in case of a close action with the white cross in the red square in the title bar

       if (window.event.clientY < 0 && (window.event.clientX > (document.documentElement.clientWidth - 5) || window.event.clientX < 15)) {

         //action to fire when leaving...
         window.opener.location.href='target.php5?pctid_toclose=<?php echo $_SESSION['pctid']; ?>';
    //  alert('user is leaving...');
     }
    }
    </script>
    ....

     

    2. targeted script (target.php) in which an action is done if needed:

    ....

     if($_GET['pctid_toclose'] === $_SESSION['pctid']) {
      //actions to do (updating DB for example)
    .....
      unset($_SESSION['pctid']);
      echo "<script type='text/javascript'>document.location.href='index.php5';</script>\n";
      exit();
     }
    .....

     

    But Renee's method is probably more reliable since my method is not working if the user click the top left icon and/or press Alt+F4... :-(

     

    Happy new year to all of you

     

    --Matt

    Tuesday, January 02, 2007 9:39 AM

All replies

  • Wondering if this issue got resolved or you were able to come up with an alternate solution.  I am running into the same problem.  Any help would be appreciated.
    Thursday, December 14, 2006 3:51 PM
  • No I have not found a valid resolution to this yet.
    Wednesday, December 20, 2006 12:20 AM
  • Hi, I had the same problem and just spent a couple of hours... It seems that "onbeforeunload" is working properly .

    The pending problem is that JS method is fired when refreshed or URL changed. I handled this inside my PHP code with the HTTP_REFERER.

    'hope that help...
    Wednesday, December 20, 2006 10:45 AM
  • Can you post an example?
    Saturday, December 23, 2006 4:40 PM
  • here is an alternate approach to running a script when a user leaves your site:

      - At the top of every script, set the session timeout to 20mins or use an application variable to set it to the IIS default.
      - Then, use the onunload or onbeforeunload events to call a script which sets the session timeout to one minute or so.
      - You then need to catch the session expiry event and call your log out code when it occurs.  In ASP you can use the Session_OnEnd event in the global.asa.

    Thus, if the user is leaving the site (by closing the window, or navigating to another site), then his session expires one minute later. If he is only refreshing the page, then as soon as the page is called, the session timeout is reset to its normal value, and he stays logged in!

    Friday, December 29, 2006 11:44 PM
  • Here is on example with the onbeforeunload :

    1. main script (script.php) in which the "leaving" is watched (NB : this script had been opened through a existing window (with a "_blank" target in the form) :

    ....

    <script type='text/javascript'>
    window.onbeforeunload = function() {
       //in case of a close action with the white cross in the red square in the title bar

       if (window.event.clientY < 0 && (window.event.clientX > (document.documentElement.clientWidth - 5) || window.event.clientX < 15)) {

         //action to fire when leaving...
         window.opener.location.href='target.php5?pctid_toclose=<?php echo $_SESSION['pctid']; ?>';
    //  alert('user is leaving...');
     }
    }
    </script>
    ....

     

    2. targeted script (target.php) in which an action is done if needed:

    ....

     if($_GET['pctid_toclose'] === $_SESSION['pctid']) {
      //actions to do (updating DB for example)
    .....
      unset($_SESSION['pctid']);
      echo "<script type='text/javascript'>document.location.href='index.php5';</script>\n";
      exit();
     }
    .....

     

    But Renee's method is probably more reliable since my method is not working if the user click the top left icon and/or press Alt+F4... :-(

     

    Happy new year to all of you

     

    --Matt

    Tuesday, January 02, 2007 9:39 AM
  • All of the above sound good, but unfortunetly I am not using ASP or PHP.  We are using JSP, do you have any further thoughts on this with JSP?
    Friday, January 05, 2007 2:23 PM
  • JSP (rather than PHP) should not be any problem since the "added-value" method is in the Javascript code and not in the PHP. What I am doing first is to send a session identification (to close) and then I am just closing the session (and removing all the session parameters...). You should be able to do so with your JSP or Web Server.
    Friday, January 05, 2007 4:06 PM
  • can you provide an example of setting the timeout in javascript?
    Friday, March 09, 2007 3:52 PM
  • I am not the author of the timeout method, but to answer your "timeout javascript" question, here is an example (form here : http://www.htmlite.com/JS018.php) :

    <script type="text/javascript">
    setTimeout("alert('Thirty seconds has passed.');",30000);
    </script>

    Good luck !

    Monday, March 12, 2007 8:42 AM


  • Hey Matt, thanks. I was searching for something similar. It works on IE7 but the condition is not to open a new tab. If you'll print the 3 values of below

    <html>
       <head>
           <script type="text/javascript">

    window.onbeforeunload=function(){

       alert("window.event.clientX="+window.event.clientX);
       alert("window.event.clientY="+window.event.clientY);
       alert("document.documentElement.clientWidth="+document.documentElement.clientWidth);

     if (window.event.clientY < 0 && (window.event.clientX > (document.documentElement.clientWidth - 5) || window.event.clientX < 15) ) {
        alert("closing window");
        }

    }
    </script>
       </head>
       <body>
           test
       </body>
    </html>

    you'll see there are some randon values for them if you do the following test:

    Open a browser, in the first tab load the code, refresh, you'll see it won't enter in that condition which is good bu tthe things are changed when opening a new tab and refresh the previous tab pretty quicly. The values for X and Y are randomized which is not that good.

    I still didn't find how to manage to cath browser close event with javascript. Any other deas? Thanks.
    Wednesday, October 10, 2007 11:25 AM
  • Hi all.

     

    I have similar problem mentioned above.

     

    The script shown in the last post works, but it is not the real solution to capture the window when is closing.

    Try this. Put the mouse pointer on the window cross and refresh the page by pressing F5. The window will close, since

    window.event.clientX is the mouse position and it is the condition to close the window.

     

    I did not resolve it yet. Detect the screenTop value works in IE6, but it doesn't in IE7. I need a similar solution that work in both versions.

     

    Please, if somebody have a solution, let me know. I've already spent a lot of time in this.

     

    Thanks a lot.

    Marcelo

    Thursday, October 25, 2007 1:40 PM
  • I tried to go closer to problem in below mentioned code but still it is not a perfect solution

     

    <script type="text/javascript">
                 var alterffourflag=0;
                 var lastkey=0;
                 var refreshflag=0;
                 document.onkeydown = function ( event )
                 {
                    event = event || window.event;
                    return window_onkeydown();
                 }
           </script>
      
      <script for=window event=onunload>
           ie7=navigator.userAgent.toLowerCase().indexOf('msie 7')!=-1;
        if(ie7==1)
        {
               if(window.document.referrer.toString()=="")//to detect popup window in the IE7
               {
                   return;
               }
                          
               var offset=0.0;
               var width=0.0;
               if( document.documentElement && ( document.documentElement.clientWidth ))
               {
                                        //IE 6+ in 'standards compliant mode'
                                        width = document.documentElement.clientWidth;
                                      
                            }
                            else if( document.body && ( document.body.offsetWidth))
                            {
                                        width=document.body.offsetWidth;
                                     
                            }
               
                  offset=18500/screen.width;
               var diff =width-offset;
               if (refreshflag!=1 && width!=0 && window.event.clientY < 0 && (window.event.clientX > (width - offset))||alterffourflag==1)
             {
                
                 
                  if( window.opener == null)
              { 
               if (window.XMLHttpRequest)
                  {
                       req=new XMLHttpRequest();
                       req.open("GET", "../ping.aspx" + "?t=" + new Date(), false);//page which removes session information
                    req.send(null);
                  }
                  else
                  {     
                   if (window.ActiveXObject)
                   {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                    req.open("GET", "../ping.aspx" + "?t=" + new Date(), false);
                    req.send(null);
                   }
                  }
              }
                  }
               refreshflag=0;   
            }
            else// IE6
            {
            
            if (self.screenTop > 10000 && event.clientY < 0 && event.clientX < 0)
            {
              
                if( window.opener == null)
                { 
               
                 if (window.XMLHttpRequest)
                    {
                        req=new XMLHttpRequest();
                        req.open("GET", "../ping.aspx" + "?t=" + new Date(), false);
                  req.send(null);
                    }
                    else
                    {     
                     if (window.ActiveXObject)
                     {
                      req = new ActiveXObject("Microsoft.XMLHTTP");
                      req.open("GET", "../ping.aspx" + "?t=" + new Date(), false);
                      req.send(null);
                     }
                    }
                }
               }
            }
              
      </script>

    <script language=javascript type="text/javascript" >
        function window_onkeydown()
        {
          var keynum
       var numcheck
       e=window.event;
       keynum = e.keyCode;
             if(lastkey==18 && keynum==115)//||(lastkey==17 && keynum==87))
       {
        alterffourflag=1;
       }
       if(keynum==116)
                {
                    refreshflag=1;
                }   
       lastkey=keynum;
     }

    </script>   

    Friday, November 30, 2007 7:06 AM
  • I am using the onunload event.

    What I did was (because that event runs on every click) this ..

     

    For each button and link on my particular page I have Javascript write to a label on screen telling the user that the page is requesting data from the server. My function that checks whether I should do anything because the browser is closing, checks to see if my "requesting data from server" message is displayed in the label, if it is then I know its a button/link click and I dont want to run my "the browser is closing code" ... if that text isn't there. The browser is closing.

     

    This works for me, i hope it helps someone else.

     

    Friday, January 04, 2008 11:08 PM
  • Hi,

     

    Is there any other way to do it, there are so many buttons and links in my page, so i can't add a label to it to say that it is retrieving data from server.

     

    I rean about event handlers but not able to use them exactly example is here

     

    <script LANGUAGE="JavaScript" FOR="window" EVENT="onunload">
    Load();
    </script>

     

    even this will be called every time you navigate with in the page.

    We can set the session time out, but even for this we need to detect/distinguish browser close from button click and navigation.

     

    Let me know if there is any other simple way...it is very urgent for me.

     

    Ramya

     

    Tuesday, February 12, 2008 2:50 AM
  • I did actually change this recently in my application.

    I still use the onunload event, but the function my onunload calls checks the active element.

     

    I noticed that this value is 'bodytag' when clicking the X to close the browser.

    Else its the button name or whatever other component on the form.

     

    Maybe this will work for you?

     

     

     if (document.activeElement.id == 'bodytag')  {

    do whatever you need to do before the browser closes.

    }

    Tuesday, February 12, 2008 6:40 PM
  • Hi,

     

    I tried with this but i am getting empty value for body tag, is there any thing else that i need to do to get the value of 'document.activeElement.id '.

     

    Let me know urgent.

    Rams

    Monday, February 25, 2008 10:14 PM
  • my apologies for the late reply and I miss typed the event you use on the page ...

    use the onbeforeunload event, this will get you your ID value.

    Thursday, February 28, 2008 7:49 PM
  • I gave the document.activeElement.id method a go.  I get the last active element id rather than a consistent return of the <Body> tag's id.  Unfortunately, we have a record locking scheme that is broken badly in this change from IE 6 to 7.

     

    Are there any other thoughts about this out there?  For the life of me, I cannot see a combination of information available to let me know when the controls on the window itself are used to close the browser.

     

    Thanks.

     

    Tuesday, March 18, 2008 7:29 PM
  •  

    Maybe I am not fully understanding your issue, you have a button (guessing as to which control you're referring to as the control on the window itself) to close the browser.

     

    Are you using .NET?

    You can use the attributes.add method to add an onclick javascript event directly to the button you're using to close the window. Then you don't need to detect anything, just add the code you want to run when that window is closed.

     

    btnName.Attributes.Add("onclick","CloseCodeFunction()")

    in the HTML of the page (aspx file), you'd add the script that contains this javascript function.

     

    The javascript onclick will run first (as its client side) then the server side code (if any) will run.

     

    Hope this helps

    Jon

    Tuesday, March 18, 2008 7:59 PM
  • Ah, forgive me.  I was not clear. 

     

    Detecting form control events is not an issue.  Detecting that the window closure was initiated by clicking the red X at the top right of the browser frame is the real issue.  In IE 6, there was a method for detecting that a method other than one of the web form's controls was used to close the window.  In IE 7, there does not appear to me to be any way to determine if that is the case.

     

     

     

    Tuesday, March 18, 2008 8:07 PM
  • Indeed, thus this thread and a few ways for trying to get around this problem.

     

    Tuesday, March 18, 2008 11:41 PM


  • I found this thread in trying to solve a very similar problem. I want to capture navigation away from my page unrelated to my links within the page. For example, user closes browser, user clicks browser home button, user uses search toolbar, etc.

    Knowing that all events typically related to navigation bubble, I just attach event handlers to the body tag. Before hand, I've added a hidden input tag with a preset value ('other site'). When the event handlers fire (I'm just looking for body.onclick), I change the value of the hidden tag ('us'). You do need to check if the source element is one that'll navigate away from page, but that's pretty easy. Then, when window.onunload (or onbeforeunload, if you care), I check the value of the hidden input field. I know right away whether the unload is one that is related to my page or not.

    It's a lot easier then trying to attach script to each tag that might navigate away from the current page. Of course, if you're doing elaborate things, including navigating via script, you'll have to modify those actions to modify the input tag.

    Holy cow! Sometimes inspiration stricks twice in the same place. If you only need to support browsers new enough to have attachEvent (IE) or addEventListener (FF and others), this is even easier (or don't mind stomping on others who might want your events using tag.onclick = myfunc). Attach the handler(s) you expect to see fire for navigation events. When one of them fires, detach your window.onunload. If you need to perform an action in either case (navigating with your site or close/navigating away), you'll want to still consider the first solution. Of course, you could also se a global script variable instead of the hidden input tag.
    Friday, March 28, 2008 9:56 PM
  • I'm using the "onbeforeunload" event.

     

    You may try this code:

     

    In the body tag, add this:

    <body onbeforeunload="handleClose()">

     

    Now, in your javascript code, add these functions:

     

    function handleClose()

    {

    if (isBrowserClosed())

    {

    // browser closed

    // do your thing...

    }

    }

     

    function isBrowserClosed()

    {

    var browserWindowWidth = 0;

    var browserWindowHeight = 0;

     

    // gets the width and height of the browser window

    if (parseInt(navigator.appVersion) > 3)

    {

    if (navigator.appName == "Netscape")

    {

    browserWindowWidth = window.innerWidth;

    browserWindowHeight = window.innerHeight;

    }

    if (navigator.appName.indexOf("Microsoft") !=- 1)

    {

    browserWindowWidth = top.window.document.body.offsetWidth;

    browserWindowHeight = top.window.document.body.offsetHeight;

    }

    }

     

    // checks if the X button was closed

    // if event.clientY < 0, then click was on the browser menu area

    // if event.screenX > (browserWindowWidth - 25), the X button was clicked

    // use screenX if working with multiple frames

    return (event.clientY < 0 && event.screenX > (browserWindowWidth - 25)) ? true : false;

    }

     

    This is working for me. Hope this helps...

    Tuesday, April 22, 2008 8:53 PM
  •  

    I tried with this problem and found partial  but working solution r

    visit at http://ginkostyle.blogspot.com/2008/07/i-have-written-code-to-detect-bowser.html to look at it

    Sunday, July 20, 2008 10:53 AM
  • Hi, i want a code that work on mozilla browser when close button click session clear

    Rest is fine at my end.

     

    Nilesh Kale

     

     

     

    Wednesday, August 13, 2008 2:45 PM
  • function doUnload()

    {

    if (window.event.clientX < 0 && window.event.clientY < 0)

    {

    // var flag

    // var mesg ="You are closing the window. do you want to continue. Click 'Ok' to close or click 'Cancel' to stay back";

    // return mesg;

    //window.alert('Do u Really want close');

    // alert("You r Logout");

    window.open('../Public/sessionlogoutsuccessful.aspx',null,'height=225,width=400')

    window.onunload = onBeforeUnloadAction();

    }

    window.onunload = onBeforeUnloadAction();

     

     

    This is my code for window close button in i.e. 6 but this code is not working in i.e.7 and firefox can you help me foe that

     

    Wednesday, August 20, 2008 7:03 AM
  • This code is working thanks my requirement is fulfil bye...................

     

    Wednesday, August 20, 2008 10:00 AM
  • Thanks for this code

    This code is run for ie7 bt foe FF it is not work if possible gice me code for FF?

    Wednesday, August 20, 2008 11:13 AM
  •  

    Thanks a lot Rey De Jesus. Your post solved one-third of my problem.

    Now, I just need to know, if we can detect click on Refresh button or File-Close, in the similar way.

    Anyways, thanks once again. 

     

    Friday, October 03, 2008 10:51 AM
  • All, 

    Code works great, but we have some users who managed to break it!

    We have one instance where this code will fail.  We have a situation where in user has placed his mouse pointer on the X button of the browser.

    In this scenario,  your code is triggering the isbrowserclosed() function coz the mouse pointer position criteria is met.

    Do we have any workaround for this scenario ?

    Thanks in advance... 

    • Proposed as answer by fmbagwell Monday, November 09, 2009 8:00 AM
    Monday, July 20, 2009 9:59 PM
  • OK, so maybe I'm late in this game, but I have come up with a way to log off a user whether they click "Log Out", close browser, or move away from site.  If it helps someone, great :) If I re-invented the wheel, what the heck.  It's been a while since I was webbing full time!

    In the following code, the LOGIN.PHP and LOGOUT.PHP were code snippets I found and modified, so for brevity I won't post.

    INDEX.PHP

    <?

     

    php
    include 'dbc.php'
    session_start() ;
    ?>

     

    <

     

    html>
    <
    head>
    <title>Moving Pros Network Web Apps</title>

    <
    script type="text/javascript">
    function doLogOut()
    {
    var target = document.createElement( "script" );
    target.setAttribute( "src", "http://mpnbusiness.com/logout.php" );
    document.getElementsByTagName( "body" )[0].appendChild( target );
    }
    </script>

    </

     

    head>

    <

     

    frameset rows="100%,*" onbeforeunload="doLogOut()" scrolling="no" border="0" frameborder="no" framespacing="0">
    <
    frame src="login.php" name="the_main" scrolling="auto" border="0" frameborder="0">
    </
    frameset>
    </
    html>

     

     

    Monday, November 09, 2009 8:05 AM
  • this code works on Chrome, but not on IE...
    Wednesday, June 30, 2010 4:49 PM
  • Hi,I tried to use ur code, its working fine in IE but its not working in Mozilla. for both close and refresh same event is firing which I dont want......So can u please update the code for Mozilla?

    Thanks

    Tuesday, January 04, 2011 12:07 PM