faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 15 people (53%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

Is there a way to know when a user has press the (x) button of the browser

Mar 23rd, 2005 07:41
HeadCircus, Nick Desipris,


I've been frustrated by the fact that onUnLoad or onBeforeUnLoad 
events do not know if you are leaving the browser or leaving the page. 
Obviously the implementation can be derived from the name of the 
event - we are just 'changing'. So until they have an onClose method, 
or something similar, I have done this in a more 'creative' way. 
The two ways the user can officially close the browser are (in my 
world)
- Escape
- Red x
I have eliminated the right click menu and the "file" command, so have 
not dealt with those directly, but perhaps similar ideas can be 
applied.
body onBeforeUnload="alertUser()"
function alertUser(){        
        if(event.keyCode == 27){ // esc
         if(confirm("close?")){    
          sendFormPost() // yes you can do this. I will edit the 
script if you want to see.        
          self.close()
        }else{
         if(event.clientX > document.body.clientWidth){
         self.close()           
         }    
        }
    }
- of course, this does limit you a little. Any action outside the 
client boundary that refreshes the page will ask you to close. So 
either you can control your browser as I have done, or you can even do 
more detection as to where the mouse was at the time of the event.