Useful scripts | Basic and Advanced Day to day used scripts

the scripts which are found rarely on the internet but needed often

window.onbeforeunload javascript code

with 2 comments

Some time you can come around a situation that you want to confirm your users about their action when they are navigating away from your page or want to close this page.

This may be a scenario of useful data transaction or a online chat system or in case youe users are editing a document and need to save it before exit.

The event which is invoked when users navigate away from a web page is onbeforeunload.
Yeah it is on before unloading the page.

So you can ask your users about their actions if they tries to navigate away or close the window by this simple and small code snippet.

<script type=”text/javascript”>

window.onbeforeunload = askUser ;

function askUser(){
  return “The changes you made will be loast if you navigate away from this page”;



Put this script in your webpage and see the code in action.

This feature you can also find in

Window.onbeforeunload picture

Written by ubk

October 16, 2007 at 3:35 pm

2 Responses

Subscribe to comments with RSS.

  1. hi,

    can you please tell me how to get the user response for the above message box

    i.e. whether the user clicked “ok” or “cancel” how can i get to know that?


    November 17, 2008 at 3:19 pm

    • You can get the user response from Confirm message box only in this way:

      answer = confirm(“Do you really want to go here?”)

      if (answer !=0)
      //User clicked OK
      //Do your work

      If you need better response types you can migrate into ASP.NET


      April 27, 2009 at 9:43 am

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: