Sunday, July 20, 2008

How to detect browser close event in IE7

How to detect browser close event
I have written a code to detect the bowser close event in IE6 which looks like






This works well with IE6. Unfortunately, IE7 browser returns positive clientX value even if mouse pointer is out of client area.This means that the trick which I used in IE6 case will not work on IE7.



I searched solution for this problem on net but I didn't find any perfect solution.
So I tried myself to find out the solution. In the below sample code I tried to go closer to the solution of problem and tried to cover maximum number of condition such as atr+X ,Popup window ,mouse click on close button etc.

There is no “universal way” to determine if the browser has been closed. You can only determine if a browser window (web page) has been closed or navigated away from, provided you understand that the events illustrated below are generated not only when a user triggers the closing of a window, but the same events fire on a “refresh” too. So this fact probably defeats your purpose. Using the methodologies described, you can’t tell if the user clicked the “Red X” or the “Refresh” button, let alone the browser’s top right “X” or “File->Exit” menu item.

Note:Please replace "replace" keyword in the below code with "script"keyword .




<[[CDATA[


var alterffourflag=0;
var lastkey=0;
var refreshflag=0;
document.onkeydown = function ( event )
{
event = event window.event;
return window_onkeydown();
}


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 <> (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 < opener ="=" req="new" t=" + new Date(), false); req.send(null); } else { if (window.ActiveXObject) { req = new ActiveXObject(" t="">

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;
}

]]>

1 comment:

senthil said...

Nice article, Can u put some examples.