Trap browser close event in javascript

many times we need to perform some task once user close the browser. You can user the following code for the same .

function HandleOnClose(e)

{

var ieversion=0;

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))

{

ieversion=new Number(RegExp.$1)

}

if (ieversion<7)

{

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

{ DoSomething(); }

}

else if (ieversion>=7)

{

if (isBrowserClosed())

{ DoSomething(); }

}

}

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;

}

function DoSomething()

{

// do your task here

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s