Click here to Skip to main content
15,881,248 members
Articles / All Topics

Window Close Event of Browser

Rate me:
Please Sign up or sign in to vote.
4.90/5 (12 votes)
16 Feb 2010CPOL3 min read 220.5K   11   17
"Window close event of browser"...

"Window close event of browser"... people are searching for this key sentence for long and have found some solutions too. But sorry to admit that there is no direct support for detecting the window close event of browser or perhaps browser's tab in HTML or JavaScript. All we have are a few nice tricks of HTML DOM (document object model) event which are used to simulate the browsers close event. Not all the codes work fine, or we can say that not all code works in all conditions.

onbeforeunload or onunload

Two of the most popular events of HTML DOM that are used to detect browser's close event are "onunload" and "onbeforeunload". Using onunload is pretty straight; just subscribe the JavaScript event. "onunload" works okay on Internet Explorer, but doesn't work fine in Mozilla Firefox. On the other hand, "onbeforeunload" works okay on both Internet Explorer and Firefox, so using "onbeforeunload" is safe. Let's look at a straight example how this is accomplished.

HTML
<script language="JavaScript">
window.onbeforeunload = WindowCloseHanlder;
function WindowCloseHanlder()
{
window.alert('My Window is reloading');
}
</script>

As you can see, this approach is pretty straight and is supposed to work. But it doesn't work always, in fact it doesn't work at all! Well these two events fire each and every time on these operations.

  • post back
  • navigate to another page
  • refresh
  • close the browser
  • close the current tab

There could be more cases that I haven't encountered yet or failed to mention, but these are the most renowned cases. As you can see that the first three cases happens very frequently, so this technique does not work. Yet there are other solutions for overcoming the problem. There is a forum discussion on that here. You can find more discussion if you Google it.

Extending the onbeforeunload Technique

If we handled the case of postback, navigate and refresh, "close event" detect will be fulfilled. So we are going to use some old fashioned technique to handle that. If you want to perform any operation in HTML using mouse, you have to click on some kind of HTML element to do that. And that's why we will trap the mouse down event. We will mark any kind of mouse down on link, button, and any element so that when post back or navigate we can detect that, it's happening because of user interaction on page. Next we will trap any special key event to make the page refresh or reload, for instance pressing Ctrl+F5, F5 and Ctrl+R can make the page refresh so we will also mark such kind of keyboard operation. So we will mark any kind of keyboard event and any kind of mouse event, other than those already mentioned in case we are not marking the Alt+f4 or the browser or tab close. So if our window close event fires, it happens definitely because of closing the browser or closing the tab. Below is a simple code snippet that is given to demonstrate the idea.

HTML
<body onbeforeunload="doUnload()" onmousedown="somefunction()">
<form id="form1" runat="server">
</form>
</body>
<script language="javascript" type="text/javascript">
var isClose = false;
//this code will handle the F5 or Ctrl+F5 key
C#
//need to handle more cases like ctrl+R whose codes are not listed here
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if(keycode == 116)
{
isClose = true;
}
}
function somefunction()
{
isClose = true;
}
function doUnload()
{
if(!isClose)
{
alert('window is closing');
}
}
</script>

Conclusion

As we have already discussed that there is no 100% fool proof way to detect the browser close event in a lot of cases, the above technique can fail. For example if the user kills the browser's process from task manager, there could be many more cases. Yet in a lot of cases, this technique can be handy. Best of luck and happy programming.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Riteq
Australia Australia
About Md. Masudur Rahman

Masudur currently works at Riteq as a software developer. Masudur Lives in Sydney, Australia.

Awards

26 May 2009: Monthly competition: Best ASP.NET article of April 2009

24 Mar 2009: Monthly competition: Best ASP.NET article of February 2009

Masudur Blog

Masudur put down his interesting learning experiences in his blog at http://munnaondotnet.blogspot.com/.

Comments and Discussions

 
QuestionBrowser close event Pin
nitesh_23826-Dec-16 9:32
nitesh_23826-Dec-16 9:32 
Questiondocument.onkeydown = checkKeycode; Pin
Member 1249508930-Apr-16 8:55
Member 1249508930-Apr-16 8:55 
QuestionImproved version: Pin
Tohid Azizi15-Feb-15 0:49
professionalTohid Azizi15-Feb-15 0:49 
GeneralMy vote of 4 Pin
Amir Mehrabi-Jorshari2-Aug-13 9:25
Amir Mehrabi-Jorshari2-Aug-13 9:25 
QuestionThis does not work for me in the iPhone Safarai and Chrome browser!! Pin
amarasat2-Oct-12 10:54
amarasat2-Oct-12 10:54 
AnswerRe: This does not work for me in the iPhone Safarai and Chrome browser!! Pin
Rahman Masudur6-Oct-12 19:37
Rahman Masudur6-Oct-12 19:37 
GeneralRe: This does not work for me in the iPhone Safarai and Chrome browser!! Pin
sozturk_198112-Mar-13 4:50
sozturk_198112-Mar-13 4:50 
GeneralRe: This does not work for me in the iPhone Safarai and Chrome browser!! Pin
aroraamit818-May-13 21:35
aroraamit818-May-13 21:35 
GeneralRe: This does not work for me in the iPhone Safarai and Chrome browser!! Pin
Tohid Azizi15-Feb-15 0:45
professionalTohid Azizi15-Feb-15 0:45 
QuestionClose event in chrome Pin
Sweetynewb13-Aug-12 20:46
Sweetynewb13-Aug-12 20:46 
GeneralMy vote of 5 Pin
kanalbrummer20-May-12 22:05
kanalbrummer20-May-12 22:05 
Found what i needed even if i didn read your whole essay. Clearly written.
QuestionCode doesn't work Pin
avay7-Dec-11 21:42
avay7-Dec-11 21:42 
GeneralMy vote of 5 Pin
shanawazway14-Nov-11 19:21
shanawazway14-Nov-11 19:21 
GeneralMy vote of 5 Pin
mohit_ranjan14329-Jan-11 1:32
mohit_ranjan14329-Jan-11 1:32 
GeneralRe: My vote of 5 Pin
ssenwerd23-Oct-11 23:07
ssenwerd23-Oct-11 23:07 
GeneralMy vote of 5 Pin
duraid wadie2-Dec-10 4:10
duraid wadie2-Dec-10 4:10 
GeneralMy vote of 5 Pin
snaseraldini28-Sep-10 1:09
snaseraldini28-Sep-10 1:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.