Warning before navigate away from a page
Posted on 19. Jul, 2008 by Sajith M.R in html

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)



Binny V A
Jul 19th, 2008
I wrote an article about this a while ago – Confirmation on Leaving the Current Page in JavaScript
www.blipoo.com
Aug 20th, 2008
Warning before navigate away from a page…
How can we prevent the navigation away from the page while doing another job…
An Nguyen
Jan 6th, 2009
This solution help me resolved my task which I take many time to find.
Thank you very!
D.Asuncion
Mar 12th, 2009
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.
rich
Mar 25th, 2009
Thanks! Simple, works.
Took
Apr 2nd, 2009
That what i want. Thank you very much.
Emre
Apr 16th, 2009
Hi ,
I need to differentiate window close and redirect to another link. Is there a way for this ?
Christopher
Jun 12th, 2009
Thanks, nice stuff.
Kaushik
Aug 6th, 2009
Great works for me!!
Hassan
Aug 22nd, 2009
This code is not working for me. Please help? I pasted this code under head tag.
iƧ giyim
Aug 24th, 2009
thank you in advance.
Naidu
Aug 29th, 2009
hi,
is there any way to remove this custom message completely. please mail me solution,.
Thanks,
Naidu
vrsanaidu@gmail.com
jeff
Dec 12th, 2009
is there a way this script could be modified to only warn someone when they are navigating away from MY website. If they’re navigating to another link on my site, then do not generate a warning.