Posts Tagged ‘Browser close’

Catch Window Close Event

May 15, 2009 8 comments

Once in a while people ask me how to catch the IE window’s close event. One thing to use is onbeforeunload event of the window. But the problem in using this event is, you never know when this onbeforeunload event is called. This event could be called for numerous reason like navigation to another page with in the application. So you cannot exactly catch the browser close event using onbeforeunload.

The mouse pointer position comes in handy in this cases. We can effectively harness the power of both onbeforeunload and clientY position to exactly catch the browser close event.


window.onbeforeunload = onunload;
function onunload()
var closeEvent=false;
if (event.clientY < 0)
closeEvent = true;

if ((closeEvent))
//Write your code here for close event.

Is there any other efficient way to do this?


Anonymous: This so very well works with internet explorer 8; i have also tested the tabs it works well. I have given the full code here. However, obviously, there is a requirement: You must allow the execution of javascript.


    window.onbeforeunload = closeit;

    function closeit() {
        var closeEvent = false;
        if (event.clientY < 0)
            closeEvent = true;

        if ((closeEvent)) {
            alert("do you want to close the window");
            //your actions during closing comes here

  <a href="">Click here to navigate to

The above code helps us to catch the window close event and there by we can do what ever we wish to do.

In some cases it is enough to just alert the user that he is trying to close the window; how to achieve it? That is even more simple; just return a string value in the closeit function

function closeit()
  return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";