How to prevent a webpage from navigating away using JavaScript?

- 5,500
- 5
- 25
- 37

- 25,147
- 16
- 58
- 68
-
What makes this page navigate away? – Niyaz May 04 '09 at 17:22
-
11According to the question, JavaScript makes it navigate away... – Shog9 May 04 '09 at 17:32
-
Possible duplicate of [How to show the "Are you sure you want to navigate away from this page?" when changes committed?](http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch) – Sam Rueby May 03 '16 at 15:30
-
@Shog9 it could be closing the tab makes it navigate away. My index finger did tha... – Bob Stein Jul 26 '19 at 11:50
10 Answers
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?";
}

- 7,728
- 2
- 31
- 38
-
But that's not enough. What about controls inside the form? They trigger this too. – Fandango68 Mar 08 '17 at 01: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 '20 at 19:05
-
2How can this be cancelled? Say a user has saved all changes and is free to leave. – Whip Jul 19 '21 at 10:17
-
3The 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 '21 at 16:45
-
1@Whip setting `window.onbeforeunload = null` seems to effectively cancel it – DrMeers Feb 21 '22 at 02:24
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.

- 6,750
- 4
- 39
- 56

- 590
- 6
- 13
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

- 136,138
- 45
- 251
- 267

- 6,518
- 3
- 43
- 52
-
2
-
If you want to remove this event listener, see: https://stackoverflow.com/a/56546665/247696 – Flimm Nov 26 '21 at 16:48
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:

- 2,043
- 2
- 21
- 24
-
3In IE if dirty is false, a string 'null' will be shown. Just wrap it inside an if statement. See: http://stackoverflow.com/questions/11793996/onbeforeunload-handler-says-null-in-ie – Jacob van Lingen Apr 13 '15 at 12:24
-
1Agreed @JacobvanLingen, this would be the best answer here and on [three](https://stackoverflow.com/q/1119289/673991) [other](https://stackoverflow.com/q/1889404/673991) [questions](https://stackoverflow.com/q/11793996/673991) 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 '19 at 11:21
-
Would this work on all browsers if it ended with undefined rather than null? – Danger Jul 26 '19 at 16:43
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;
}

- 1,030
- 3
- 12
- 23
-
2Unless the browser is Opera, which skips the onunload event if the tab/window/program is being closed. – Powerlord May 04 '09 at 17:35
-
The equivalent to the accepted answer in jQuery 1.11:
$(window).on("beforeunload", function () {
return "Please don't leave me!";
});
altCognito's answer used the unload
event, which happens too late for JavaScript to abort the navigation.

- 6,337
- 6
- 33
- 59
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."

- 6,696
- 3
- 46
- 36
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.

- 6,440
- 2
- 35
- 38
Use onunload.
For jQuery, I think this works like so:
$(window).unload(function() {
alert("Unloading");
return falseIfYouWantToButBeCareful();
});

- 523
- 2
- 9
- 22

- 41,026
- 12
- 101
- 131
-
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 '11 at 09: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 09 '12 at 10:50
If you need to toggle the state back to no notification on exit, use the following line:
window.onbeforeunload = null;

- 89
- 2
- 7