tags:

views:

437

answers:

2

Hi, I have a requirement that when the user clicks on [X] button of the browser, I should give them a message.

I accomplished this task using the onUnload method of JavaScript.

Now, if even I refresh the page, then also the same message appears!

Why this is so and how to overcome?

The code is here

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <script language = "javascript">

function Message()

{ alert("Are you sre you want to leave?"); }

</script> </HEAD>

<BODY onUnload="Message();"> </BODY></HTML>

Please help

+3  A: 

That's correct behavior: refreshing the page involves unloading it and then loading it again.

The best way to approach such a confirm dialog is with code like this:

<script language="javascript" type="text/javascript">
window.onbeforeunload = function() {
    return "You have unsaved changes.";
}
</script>

This is the mechanism you see, for example, on GMail if you try to close a page when your message hasn't been saved or sent yet. It will still fire when attempting to refresh the page, so it's important to ensure you only return an error string if there really is unsaved work.

Please keep in mind that there's no guarantee the onUnload or onBeforeUnload events will fire, since there's no guarantee your visitor will even have enabled JavaScript, so you shouldn't use this for anything more than a friendly reminder about unsaved work.

VoteyDisciple
+1 "You have unsaved changes" is the only good reason for an unload confirmation. Sites that pester with "please stay looking at this lovely site" leaving messages are a crime against the web, and designers that produce them are subject to prosecution and harsh punishment at the International Court of Web Justice.
bobince
bobince for web presidency! :)
vsync
+2  A: 

There is, unfortunately, no javascript event to detect the clicking of the X button (closing of the browswer). The closest we come is the onunload or onbeforeunload events. And, yes, they fire regardless of the method that the user chooses to navigate away from the page. Whether by closing the browser, clicking a link, entering another URL, or reloading a page. This is what you've discovered.

Don't know if this will solve your problem since we StackOverflowers don't know about your app, but you could create a kludge similar to this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head> 
<script language = "javascript">
function Message()
{
    if (reallyExiting) alert("Are you sre you want to leave?");
}

</script>
</head>
<body onLoad="reallyExiting=true" onUnload="Message();">
<a href="example.html" onClick="reallyExiting=false">Not really leaving</a>
<a href="http://www.someOtherSite.com"&gt;Really leaving</a>
</body>
</html>

I know it's rough, but you could use some similar variable to keep track of what links they've hit or not hit as the case may be.

HTH.

Rap