Click to See Complete Forum and Search --> : Can onUnload tell if X was clicked?


airplays
May 20th, 2002, 11:17 AM
Is there a way for the OnUnload event to tell whether the user clicked X to close the brower session, or just clicked on a link?

Thanks!

websmith99
October 3rd, 2002, 09:39 PM
Only through a roundabout way -

You could initialize a JavaScript variable, "clickedOnX" to be true:

clickedOnX = true;

Then EVERY link on the page sets this variable to false:

<a href="nextpage.jsp" onclick="clickedOnX = false;">next</a>

The OnUnload event calls a function that checks the value of this variable. If it's true, then you know that the "x" closed the browser.

Example:


<html>
<head>
<script language="JavaScript" type="text/javascript">
clickedOnX = true;

function checkUnload() {
if (clickedOnX) {
alert("Why did you close the browser?");
return false;
}
}
</script>
</head>
<body onUnload="checkUnload()">
<a href="nextpage.jsp" onclick="clickedOnX = false;">next</a>
</body>
</html>

Note that the alert message will display after the browser closes.