How to prevent a webpage from navigating away using JavaScript?
-
What makes this page navigate away? – Niyaz May 4 '09 at 17:22
-
10According to the question, JavaScript makes it navigate away... – Shog9 May 4 '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? – Sam Rueby May 3 '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
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?";
}
-
11The browser will display an appropriate prompt. Simply use
window.onbeforeunload = function() { return ""; }
– KIM Taegyoon Nov 17 '16 at 8:54 -
But that's not enough. What about controls inside the form? They trigger this too. – Fandango68 Mar 8 '17 at 1:59
-
1Modern browsers do not allow you to display a custom message in the prompt, as this was abused by phishers and the like. – Flimm Dec 3 '19 at 17:06
-
Thanks @Flimm, I've updated the answer so it is now accurate for current browsers. – Jimmie R. Houts Dec 3 '19 at 22:30
-
@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? – Nasimba Mar 29 '20 at 19:05
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.
-
how show modal if user want close browser(click on close)? it really? – user2881809 Mar 20 '14 at 14:46
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:
-
3In IE if dirty is false, a string 'null' will be shown. Just wrap it inside an if statement. See: stackoverflow.com/questions/11793996/… – Jacob van Lingen Apr 13 '15 at 12:24
-
-
Would this work on all browsers if it ended with undefined rather than null? – Danger Jul 26 '19 at 16:43
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
-
2
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;
}
-
2Unless the browser is Opera, which skips the onunload event if the tab/window/program is being closed. – Powerlord May 4 '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.
Use onunload.
For jQuery, I think this works like so:
$(window).unload(function() {
alert("Unloading");
return falseIfYouWantToButBeCareful();
});
-
Returning false will not cancel the unload unfortunately - the
unload
event fires when the user is leaving the page, unlikebeforeunload
which fires just beforehand (and may be cancelled) – Jimbo Sep 28 '11 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 '12 at 10:50
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."
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.