Tuesday, August 16, 2011

"onbeforeunload" An Illustration/Demo

I recently happened to work with a stuff that required javascript operations to be performed, when a user navigates away from a page or closes it on a browser.

So I ended up discovering the presence of this event "onbeforeunload" for html pages. Though this seems to have some issues with the Opera browser, It seems to work fine with IE, Firefox and Chrome. Haven't tested on safari. The code that helps me do it is quite fascinating as well.

A function named confirmExit() exists that just works like the confirm prompt, which provides with default options asking your opinion on leaving or staying on the same page. The code is as follows

<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>

Following is a  screen shot of how these pages look on various browsers














 
Hope this helps :)



2 comments:

  1. You don't want to do that in a production system unless you want to p**s your users off. What you would do is to keep a flag that is set to true if any of the fields has been changed by the user or any refresh is pending and only then pop the question.
    But I presume you know that.

    ReplyDelete
  2. lol:)

    Just intended to share the idea. U r absolutely correct and I agree with you. Any ways its is up to us to use things in a smart way right....

    :)

    ReplyDelete