Warning before navigate away from a page
- 8 Comment

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
-
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 -
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 -
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 -
rich said:
Thanks! Simple, works.
March 25th, 2009 at 3:07 am -
Took said:
That what i want. Thank you very much.
April 2nd, 2009 at 9:45 am -
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 -
Christopher said:
Thanks, nice stuff.
June 12th, 2009 at 12:15 pm

Warning before navigate away from a page…
How can we prevent the navigation away from the page while doing another job…