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:


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;


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)

18 thoughts on “Warning before navigate away from a page

  1. jeff

    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.

  2. NG

    While beneficial when working on documents or similar programing on your private network or computer. this type of software when browsing the Internet is often percieved as browser hijacking requiring the visitor to install extra security, blocking and script to browser to prevent it. In many cases most people will simply close their browser or worst case reboot to escape. It’s simply rude to try to keep visitors in the hopes they’ll click an ad. However it’ is useful in saving work done on a private computer. Which is the only place it should ever be found.

  3. NG

    Just an additional note for those trying to escape a rude webmasters use of this. In Firefox hit tools, options and click the Java script box. Similar means are available for other browsers. Again to reiterate. “Are you sure you want to go somewhere else?” should only be on a private or secure network and used solely for form purposes, not to hijack a visitor to stay on your online website.

Leave a Reply