176

How to prevent a webpage from navigating away using JavaScript?

4

10 Answers 10

215

Using onunload allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload will interrupt navigation:

window.onbeforeunload = function() {
  return "";
}

Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.

In older browsers you could specify the message to display in the prompt:

window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
}
5
  • But that's not enough. What about controls inside the form? They trigger this too.
    – Fandango68
    Mar 8, 2017 at 1:59
  • @FlimmI want to update the user online status when online users close the browser tab or browser.I used the code in the solution but it didn't work.Is there a solution for this?
    – Mustafa
    Mar 29, 2020 at 19:05
  • 2
    How can this be cancelled? Say a user has saved all changes and is free to leave.
    – Whip
    Jul 19, 2021 at 10:17
  • 3
    The problem with this is that you might be overwriting another window.onbeforeunload function. Instead, it is better to run window.addEventListener('beforeunload', function() {});
    – Flimm
    Nov 26, 2021 at 16:45
  • 1
    @Whip setting window.onbeforeunload = null seems to effectively cancel it
    – DrMeers
    Feb 21, 2022 at 2:24
28

Unlike other methods presented here, this bit of code will not cause the browser to display a warning asking the user if he wants to leave; instead, it exploits the evented nature of the DOM to redirect back to the current page (and thus cancel navigation) before the browser has a chance to unload it from memory.

Since it works by short-circuiting navigation directly, it cannot be used to prevent the page from being closed; however, it can be used to disable frame-busting.

(function () {
    var location = window.document.location;

    var preventNavigation = function () {
        var originalHashValue = location.hash;

        window.setTimeout(function () {
            location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
            location.hash = originalHashValue;
        }, 0);
    };

    window.addEventListener('beforeunload', preventNavigation, false);
    window.addEventListener('unload', preventNavigation, false);
})();

Disclaimer: You should never do this. If a page has frame-busting code on it, please respect the wishes of the author.

1
  • how show modal if user want close browser(click on close)? it really?
    – user2881809
    Mar 20, 2014 at 14:46
28

The equivalent in a more modern and browser compatible way, using modern addEventListener APIs.

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

3
  • 3
    Remember to correctly capitalise event.returnValue
    – Flimm
    Dec 4, 2019 at 8:33
  • If you want to remove this event listener, see: stackoverflow.com/a/56546665/247696
    – Flimm
    Nov 26, 2021 at 16:48
  • In TypeScript, you'll need to mark event: BeforeUnloadEvent otherwise you'll get returnValue is deprecated. Sep 9 at 15:26
16

I ended up with this slightly different version:

var dirty = false;
window.onbeforeunload = function() {
    return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}

Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.

With the text in the selected answer you see redundant prompts:

enter image description here

3
  • 3
    In IE if dirty is false, a string 'null' will be shown. Just wrap it inside an if statement. See: stackoverflow.com/questions/11793996/… Apr 13, 2015 at 12:24
  • 1
    Agreed @JacobvanLingen, this would be the best answer here and on three other questions if it ended in undefined instead of null. (1) it's conditional (2) it mentions "dirty" the most common legit reason to hinder navigating away and (3) it has a screenshot.
    – Bob Stein
    Jul 26, 2019 at 11:21
  • Would this work on all browsers if it ended with undefined rather than null?
    – Danger
    Jul 26, 2019 at 16:43
7

In Ayman's example by returning false you prevent the browser window/tab from closing.

window.onunload = function () {
  alert('You are trying to leave.');
  return false;
}
2
  • 2
    Unless the browser is Opera, which skips the onunload event if the tab/window/program is being closed.
    – Powerlord
    May 4, 2009 at 17:35
  • This simply does not work anymore, if it did at some point :) Jun 30, 2021 at 6:53
6

The equivalent to the accepted answer in jQuery 1.11:

$(window).on("beforeunload", function () {
    return "Please don't leave me!";
});

JSFiddle example

altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation.

4

That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.

In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).

A more appropriate error message might be:

window.onbeforeunload = function() {
    return "If you leave this page, you will lose any unsaved changes.";
}

Or stackoverflow style: "You have started writing or editing a post."

4

If you are catching a browser back/forward button and don't want to navigate away, you can use:

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

Otherwise, you can use the beforeunload event, but the message may or may not work cross-browser, and requires returning something that forces a built-in prompt.

3

Use onunload.

For jQuery, I think this works like so:

$(window).unload(function() { 
  alert("Unloading"); 
  return falseIfYouWantToButBeCareful();
});
2
  • Returning false will not cancel the unload unfortunately - the unload event fires when the user is leaving the page, unlike beforeunload which fires just beforehand (and may be cancelled)
    – Jimbo
    Sep 28, 2011 at 9:36
  • @altCognito: You gave me good idea with falseIfYouWantToButBeCareful() Now i can avoid the default pop up given by IE or FF. But for chrome it is not working. Looking into it.
    – user367134
    Aug 9, 2012 at 10:50
1

If you need to toggle the state back to no notification on exit, use the following line:

window.onbeforeunload = null;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.