Saturday 19th July 2008
by Sajith M.R
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)
Tags: , away, block, close, confirm, Javascript, navigate, save, warning
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.
hi,
is there any way to remove this custom message completely. please mail me solution,.
Thanks,
Naidu
vrsanaidu@gmail.com
thank you in advance.
This code is not working for me. Please help? I pasted this code under head tag.
Great works for me!!
Thanks, nice stuff.
Hi ,
I need to differentiate window close and redirect to another link. Is there a way for this ?
That what i want. Thank you very much.
Thanks! Simple, works.
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.
This solution help me resolved my task which I take many time to find.
Thank you very!
Warning before navigate away from a page…
How can we prevent the navigation away from the page while doing another job…
I wrote an article about this a while ago – Confirmation on Leaving the Current Page in JavaScript