Home > javascript, Scripts > window.onbeforeunload javascript code

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 wordpress.com

Window.onbeforeunload picture

About these ads
  1. samsami2u
    November 17, 2008 at 3:19 pm | #1


    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?

    • ubk
      April 27, 2009 at 9:43 am | #2

      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

  1. No trackbacks yet.
You must be logged in to post a comment.

Get every new post delivered to your Inbox.

Join 40 other followers

%d bloggers like this: