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
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:
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
onUnloadoronBeforeUnloadevents 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.