Hi,

I want to execute some java script code when I close the browser. The following code is executing in I.E. But I want to execute in Firefox and Netscape.

<html>
<head>
<script language="JavaScript">

function doUnload(evt)
{
var e = (window.event) ? window.event : evt;

if (e.clientX < 0 && e.clientY < 0){
{

alert("window closing....");

}
}

</script>

</head>
<body onunload="doUnload(event)">

</body>
</html>

In firefox clientX and clientY are getting as "undefined"....

Can any One Please help me.

Thanks in advance

Deepthi

This a a cross browser compatible script for finding out the mouse coordinates using Javascript. Referred from this site.

function doSomething(e) {
        var posx = 0;
        var posy = 0;
        if (!e) var e = window.event;
        if (e.pageX || e.pageY)     {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)     {
            posx = e.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
        }
        alert(posx + ", " + posy);
    }

Hi,

Thanks for your reply..

I am getting the mouse coordinates in IE, but not in firefox using the above codes.

My requirement is to execute some function while closing the browser window. It should not work while refreshing the page.

Thank you.

The coordinates are working fine in my case. There must be some error on your part. Post the code if it still doesn't work.

As for executing a function when the window closes, you can use the onunload callback function.

Here is an example:

<html>
<head>
<script>
    function doSomething(e) {
        var posx = 0;
        var posy = 0;
        if (!e) var e = window.event;
        if (e.pageX || e.pageY)     {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)     {
            posx = e.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
        }
        alert(posx + ", " + posy);
    }
    
    function confirmMe()
    {
        alert("Thank you for visiting us!!");
    }
</script>
</head>
<body onunload="confirmMe();">
    <div onclick="doSomething(event);">Hello there</div>
</body>
</html>

Yes, the code is detecting the mouse coordinates. But it is working when REFRESHING the page and on every other button events(back button..) .

Is there any possible way to execute some functions, only on closing the browser window(in firefox)?

Thank you.

> Is there any possible way to execute some functions, only on
> closing the browser window(in firefox)?
As far as I know, no.

Even if you could do that, Firefox closes so quickly that nobody could read it.

If somebody clicks the X, they want to close the program now. They don't want it to do any more.

If IE can do it, it is because IE has a nonstandard extension to web code. Never use nonstandard code.

> Even if you could do that, Firefox closes so quickly that nobody could read it.
The 'onunload' event fires before the browser is closed and if an alert is fired, stops the window from closing so 'closes so quickly' is not an issue as such. The problem here is that the OP wants a function which would be fired _if and only if_ the browser is closed which I don't think is possible using any standard way.

My purpose is to delete a record from the database table while closing (only) the browser window using X.

AFAIK, you can't do that since before the document is being unloaded, submitting the form is an illegal action.

Even if you could do that, Firefox closes so quickly that nobody could read it.

If somebody clicks the X, they want to close the program now. They don't want it to do any more.

If IE can do it, it is because IE has a nonstandard extension to web code. Never use nonstandard code.

IE can't do this either.

The standard doesn't well indicate whether onunload should be called when a browser window is closed, or if the browser is closed, or when the page is changed. It says:

W3C Event Model Specification for 'onunload' : "The onunload event occurs when the user agent removes a document from a window or frame. This attribute may be used with BODY and FRAMESET elements."

Since techincally, the document is never in a window or frame ( it's on a server silly! ) there's no real necessity to implement onunload, or onload >_>

Seriously; browser developers shouldn't implement this EVER. It's too much of an annoyance. You get 'web developers' making sites that have onload="return false;" onunload="window.location = 'elsewhere'" onunload="window.open('dont_leave.html')" onunload="while(1){alert('Come back!');}" et-cetera.

Opera doesn't call onunload, when going backwards and forwards between pages - with good reason; it remembers javascript state between pages; thus, the javascript is not unloaded in the normal sense. I suppose then, in Opera certainly, you're more likely to get an unload fired if and and only if the browser is closed. However, I'm pretty sure that closing the application stops javascript, thus ignoring remaining events. It should.

Firefox, I don't know. Do they remember JS state through navigation history?

Heh. I read that article and comments before making the post.. I'm firmly on the "it's not a bug" side of the fence, although it may or may not be a misinterpretation of the specification, which is another matter entirely. Looking at that Mozilla link makes me think that Opera have done it better ( by avoiding it ).

It has annoyed me in the past, that onunload doesn't work the same everywhere. But I can't think of a single case where it's truely neccessary to do something when a user 'unloads' a page, at least not any case that can't be worked around by looking at the problem in a different way.

Besides; you can never tell if a user turns the computer off, or sends a terminate signal to the browser, or unplugs their net connection ( ok, you can.. but you can't tell which one they did ).

It seems that you have never interacted with clients who insist on having a 'popup' window or some clean up routines to be performed when the user attempts on closing or unloading the window. Though this may seem like a nonsense requirement for public domain sites, it becomes a nifty feature for intranet sites.

Even Google makes use of this confirmation thingy (try composing a mail and going back to inbox without sending it) by either using the 'onunload' event or some other trick for rich and interactive user experience. Come to think of it, when you think of web revolution in terms of applications which behave more and more like the desktop applications, the onunload suddenly seems to be a required feature.

Think out of the box and you would see of the different ways in which you can use such events for the betterment of applications as well as UI.

My personal experience has been that Opera scales the worst when it comes to handling events displaying the most random behavior.

hi,
this code works fine but not like we want, to check if browser getting closed we need to get the x,y co-ed where mouse get clicked, if its less than 0 then its getting closed. but to send an event in firefox we need to perform some action like it says click "Hello There", event will go when we'll click Hello There, but we want to send the event onunload, which is ok with IE but not with FF, firefox sends event unintialized/undefined, so its hard to find the co-ed and to check it FF getting closed or not.

Even if you could do that, Firefox closes so quickly that nobody could read it.

If somebody clicks the X, they want to close the program now. They don't want it to do any more.

If IE can do it, it is because IE has a nonstandard extension to web code. Never use nonstandard code.

Such a nonsense!@
What a demagogy, hahahaha

Really not nonsense, There's nothing in standard HTML + JS that mandates the existance of a _window_ let alone an event when it closes. Each browser handles its idea of a 'window' in a different way. Maybe this is a shortcoming in HTML + JS, but, that's just the way it is.

The standard doesn't well indicate whether onunload should be called when a browser window is closed, or if the browser is closed, or when the page is changed. It says:

Standards ?!
"Browser window" meaning "a browser".
The so called "Standards" don't indicate if internet should exist at all neither, but it exists.

W3C Event Model Specification for 'onunload' : "The onunload event occurs when the user agent removes a document from a window or frame. This attribute may be used with BODY and FRAMESET elements."

Since techincally, the document is never in a window or frame ( it's on a server silly! ) there's no real necessity to implement onunload, or onload >_>

On top of a sillynes of W3C using the word "remove" the document from the window..., when the correct word is "unloading" the document from the window, (that is: the window of interpreter application for particular document equipped with browsing capability) and you
saying that the "document is on the server" is more than wrong . Because if it was possible to view documents residing on a server without downloading them first - we would be surfing the net with the speed of light. Wouldn't we?!

You are somehow managing to ignore the fact that it's impossible for the page to get rendered and displayed before it gets cached. So practically, technically theoretically or whatever, - that statement is false. Because the page is loaded on the browser and that, smart browser will always know when it has started loading; when it has become interactive and also when it finished loading. Less smart browsers don't know when the page has started loading neither when it became interactive etc but they suddenly become aware of it only when it allready finished loading. Other dumber browsers shouldn't know this either.

I have to agree that old static generation browsers don't need the onload event to fire at all 'cause they can't do a thing with it. It is loaded when it loads.

This sounds as if you're proposing that we shuld go back to the time when you could use only html tags? I have to admit - life would be so damn easy, -but boring.

Seriously; browser developers shouldn't implement this EVER. It's too much of an annoyance. You get 'web developers' making sites that have onload="return false;" onunload="window.location = 'elsewhere'" onunload="window.open('dont_leave.html')" onunload="while(1){alert('Come back!');}" et-cetera.

You are again missing the "target" - or is it the "source element"?
Are you suggesting that browser developers are to blame that you visit "x*x" webpages? That we should sue browser developers, because coders of some irresponsible barely legal agencies are forced to use advanced browser capabilities, in near criminal manner like some you've just mentioned?

Guess Not!
Your "target" is not the "source" of evil. Nothing is evil by itself. It depends on "who" is using it and of course "how". Shortly:WhoHow :)
It all depends on coders like you and me. - You should never allow yoursef to missuse a perfect browser functionality... If you buy a gun and kill an inocent, it's not the manufacturers fault, it's yours.

p.s.:
And you are also wrong when saying that if it only works in internet explorer it doesn't work. Pure internet dogma. Only ie6 has a sharee of more than 50% of browser agents, without counting lower ie versions and a great share ie7 has.

On contrary, in real world if something doesn't work in ie, will surely mean that it doesn't work at all. Since IE's are more than 70% of the browsers that will hit your page.

Opera doesn't call onunload, when going backwards and forwards between pages - with good reason; it remembers javascript state between pages; thus, the javascript is not unloaded in the normal sense. I suppose then, in Opera certainly, you're more likely to get an unload fired if and and only if the browser is closed. However, I'm pretty sure that closing the application stops javascript, thus ignoring remaining events. It should.

Smart browsers should make a distinction between: navigating away from the current page and/or from the current domain etc against application close.
But they don't!
I guess opera decided to neglect this event completely. Because events either happen - or they don't; in casse they happen, and there is a listener, - they get "on TV" no matter what. But in Operas casse the listener is not engaged.

Even Google makes use of this confirmation thingy (try composing a mail and going back to inbox without sending it) by either using the 'onunload' event or some other trick for rich and interactive user experience. Come to think of it, when you think of web revolution in terms of applications which behave more and more like the desktop applications, the onunload suddenly seems to be a required feature.

There you are, - you've made a good point.

Think out of the box and you would see of the different ways in which you can use such events for the betterment of applications as well as UI.

My personal experience has been that Opera scales the worst when it comes to handling events displaying the most random behavior.

I totally agree. Opera is a beautiful browser but its to damn non "traditional" in its behavior, especially when it comes to keyboard navigation.

As for the question asked: i think our friend should change the aproach to hisproblem and see what others are using for the same purpose; google keyword "session expire" purhaps?

In my comment about the document being on a server; I'm pointing at the sillyness you also note in the W3C's wording: that of an implied concept of a browser 'removing' a document from some kind of tangible 'window'. Regardless of caching ( which isn't mandated by HTML either and is thus an 'implementation detail' ), the document is never actually 'moved' anywhere, just copied. When a browser actually unloads a document is even more difficult to define, though. It's not effecient to actually 'unload' all pages when going back and forth through them. ( EDIT: or, in terms of video memory, it's effecient to 'unload' the graphical manifestation of a page when ALT+Tabbing.. is this desired?.. This part of the standard hasn't really been updated since tabbed browsing/more interactive sites became popular, but, it's what you/we have to deal with )

I want webpages to stay mostly static, yes. Do what you want within reason at the server, but send HTML + CSS + simple JS to the client.. This model is 'traditional', and works for nearly everything that a person might use the World Wide Web ( i.e. a browser ) for. The 'application' model ( i.e. GUIs, realtime, events, etc ) is nearly always better served by actual applications; be those Internet-enabled or otherwise. There's too many reasons why for me to list here without writing a small essay, but I'm sure you know what I mean..

I wouldn't suggest going backwards; just moving forwards in the right direction.

I can't find a point in your comments on my signature; for explanation, I'm saying "design your site so it works in my alternative standards-compliant browser, or I don't consider it to be a working website". I don't really give a rats about the market share of another browser if all I see is an empty screen on primary browser : I just go elsewhere.

I think that "load/unload" the document is the only appropriate notion to use in situations when:
1. user is closing the current page [ap dependable op] currently associated with ap. close;
2. the user is loading [as a final step of download, cache, parse, render procedure] a New Page in the same docked browser window (called browser tab while in fact being just another instance of an independent dock-able browser window), causing the previous page to be unloaded from active memory and free the space previously taken by its content.
3. Moving back and forth the browser history, inside the same tab/docked window, should be considered as load/unload process, -moreover, this action should factually cause the page to get "loaded/unloaded" from active memory, snce it already exists in a browser cache and there is absolutely no practical reason to leave it "eat" your system resources as last generation browsers do.

This undoubtedly means that: if the user closed the page he was on (although I don't know if there is such browser providing that option), opened another page in the same window/browser tab, navigated back and forth, should all actually carry out the task, to unload/load content, while, same time triggering corresponding events. But I think that browser close should be discerned from document close which is an equivalent of page unload, but this two different actions/events have in practice, the same meaning for the page content therefore right now it is unnecessary to discern. Although browser close and /or tab close comparing to page close/unload, should have different meanings on the browser domain, wihch I believe are already differentiated.
*
But it's a completely different story when (ctrl) tabbing or alt+tabbing between browser windows containing data. This doesn't fall in navigating category. In this case: only the screen display gets redrawn, but nothing else. No events should fire nor any other action be carried out except window/tab focus with any other focus event aliases. Meaning, only the conventional (focus/blur) events should fire. Smart browsers will during this event (focus) check if any content changes have occurred on the side of source provider and update if specified or some other way required.

Generally speaking There's nothing more efficient than loading pages from browser cache. Keeping them in memory causes what f.i. firefox users are complaining the most: memory leaks.

Regards.

but wat is the solution

Seems my solution is better.

<head>
<script>
var jmp=false;
function jmp(){
if(jmp){
      location.href='ExecCmd?exitClr=1';
}
}
</script>
</head>
<body onload="change();" onunload="jmp();">
</body>

Set the jmp to define jump or not.
It works fine in IE but partially in Firefox.

Member Avatar for Rhyan

Ok, guys, why do we need such a word fight for nothing?

Actually I did not understand what is exactly the requirement - I mean, does the guy want to have the code work in any browser window on closing it, or he just wants to do something upon closing a specific window only.

If he needs to do something only in a specific window, he can call the specific window using window.open() - just like a popup.... Then the window.close() method will close only this specific window.
As the window.close() can be called within another function, the guy can just create a new closing function, linked on a specific close button.
So it looks like
function myclosingfx()
{
do whatever i want to do;
if (doing this successful)
{
window.close();
}
}
Then just put a button on top of the page - close me with action onclick="myclosingfx()"

And that's that.

Unfortunately as far as I know onunload cannot distinguish between navigating to another page or simply closing the window, so I think it cannot be used in this case. So I don't have a solution for let's say - any browser window...just for the popus...

Hi,
Even I am trying the browser close event for cross browser and this should trigger only when X button is clicked or page is refreshed. Here's the code I am using but it only works in IE:

=====================

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><head>
<title>Warning Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script language="JavaScript">

// warning message javascript

var isOpera, isIE, isNav, isFox, isOther = false;
if (navigator.userAgent.indexOf("Opera") != -1) {
isOpera = true;
} else if (navigator.userAgent.indexOf("Firefox") != -1) {
isFox = true;
} else if (navigator.appName == "Microsoft Internet Explorer") {
isIE = true;
} else if (navigator.appName == "Netscape") {
isNav = true;
} else {
isOther = true;
}

if (isIE || isOpera || isNav || isFox || isOther) {
window.onbeforeunload = WarnUser;
function WarnUser() {
OffsetX = window.event.clientX;
OffsetY = window.event.clientY;
if (((window.event.clientX < 0) || (window.event.clientY < 0))
&& (isWarnUser == true)) {
event.returnValue = " ";
//window. önunload = sessionInvalidate;
} else {
// Reset the flag to its default value.
isWarnUser = true;
}
}
}




</script>

</head>
<body>
<script type="text/javascript">
var isWarnUser = true;
</script>
test
</body>
</html>

========================

I know the issue is because of window.events and ClientX/ClientY.
Could someone please fix my code to make it work in all browsers? This is very urgent and have been striving since 3 days...

*Please Note: Current code is working in IE only and to check you have to close the browser window or refresh the page with mouse click.

<html>
<head>
<script language=javascript>

function doSomething(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;

if (e.pageX || e.pageY) 
{
	posx = e.pageX;
	posy = e.pageY;
}
else if (e.clientX || e.clientY) 
{
	posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
	posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
	alert(posx + ", " + posy);
}
function confirmMe()
{
alert("Thank you for visiting us!!");
}


function help(e)
{
	if (!e) var e = window.event;	
	if (e.onclick)
	{
		document.getElementbyID("id2").style.display="block";
		alert("ethe");
	}
	else
	{
		document.getElementbyID("id2").style.display="none";
		alert("hgere");
	}



}
</script>
</head>
<body onunload="confirmMe();">

<div onclick="doSomething(event);">Hello there</div>

<table border =2>
	<tr id='Id1'>
		<Td><input type=button name="Test" Value="Test" onclick="javascript:help(event);">	</td>
	</tr>

	<tr id='id2' style="display:none">
		<td><input type="text" id="text1" value="">
		</td>
	</tr>
</table>

</body>
</html>

Hi Govind - This is how it should not work...You might have misunderstood the requirement...

commented: sir can u help me how to use to window.event.srcelement +0

window event srcelement in firefox hw we use this ???

hi Deepthi,

I have also same problem. If you got answer please post on the same link.
please help me.


thanks
Satish

Hi,

I want to delete a row in DB when browser is closed.
I tried onunload and onbeforeunload but they are called everytime when I navigate from one JSP page to another JSP page and also if I refresh the page.

My requirement is to call that function only when the browser is closed.

Please help ASAP

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.