Jul 19 2008

Warning before navigate away from a page

In some cases, if you are in between any work of editing or typing a content, and you wont let the visitor to navigate away from the page without particular condition, say the document is not saved yet, you can block the navigation (even the closing of the browser window) with Javascript.

Here is the javascript code for that:


<script>

window.onbeforeunload = function (evt) {
var message = ‘Are you sure you want to leave?’;
if (typeof evt == ‘undefined’) {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}

</script>

Just paste this code anywhere in your html page. The condition settings , warning messages are up to you. In the above code, the warning will be displayed when ever a navigation happen (Even closing of browser window happen)

(pic from Binney V.A)

8 Comments on this post

Trackbacks

  1. www.blipoo.com wrote:

    Warning before navigate away from a page…

    How can we prevent the navigation away from the page while doing another job…

    August 20th, 2008 at 11:07 am
  1. Binny V A said:

    I wrote an article about this a while ago - Confirmation on Leaving the Current Page in JavaScript

    July 19th, 2008 at 11:07 pm
  2. An Nguyen said:

    This solution help me resolved my task which I take many time to find.
    Thank you very!

    January 6th, 2009 at 2:37 pm
  3. D.Asuncion said:

    Olahhhh… Nice Idea..

    Good Day, i have a question in debugging, how can i detect in code behind when i click “Ok”?

    Thanks in Advance.

    March 12th, 2009 at 7:33 am
  4. rich said:

    Thanks! Simple, works.

    March 25th, 2009 at 3:07 am
  5. Took said:

    That what i want. Thank you very much.

    April 2nd, 2009 at 9:45 am
  6. Emre said:

    Hi ,
    I need to differentiate window close and redirect to another link. Is there a way for this ?

    April 16th, 2009 at 8:30 pm
  7. Christopher said:

    Thanks, nice stuff.

    June 12th, 2009 at 12:15 pm

LEAVE A COMMENT

Subscribe Form

Subscribe to Blog

Recent Comments

  • Sajith M.R: Press shift and enter key for a new line in chat
  • Borellus: Nice little function there, I think I may try to use it at some point.
  • Abhishek: Can we have newline characters…. i want something like this Line 1 Line 2 Line 3
  • Joanne Cox: Thanks for sharing this; your input is appreciated and has made me change my opinion slightly. About the...
  • Saboor: hi i also want to implement a chatting like Gmail or FaceBook , please, email me the source code on...

Recent Posts