window.onbeforeunload javascript code

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


2 thoughts on “window.onbeforeunload javascript code

  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?

    • 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

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s