Prevent a webpage from navigating away using JavaScript

JavascriptOnbeforeunload

Javascript Problem Overview


How to prevent a webpage from navigating away using JavaScript?

Javascript Solutions


Solution 1 - Javascript

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?";
}

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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;
}

Solution 6 - Javascript

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.

Solution 7 - Javascript

Use onunload.

For jQuery, I think this works like so:

$(window).unload(function() { 
  alert("Unloading"); 
  return falseIfYouWantToButBeCareful();
});

Solution 8 - Javascript

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."

Solution 9 - Javascript

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.

Solution 10 - Javascript

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

window.onbeforeunload = null;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSoftware EnthusiasticView Question on Stackoverflow
Solution 1 - JavascriptJimmie R. HoutsView Answer on Stackoverflow
Solution 2 - JavascriptanarchocuriousView Answer on Stackoverflow
Solution 3 - JavascriptPaul WeberView Answer on Stackoverflow
Solution 4 - JavascriptDangerView Answer on Stackoverflow
Solution 5 - JavascriptgaborView Answer on Stackoverflow
Solution 6 - JavascriptBoffinBrainView Answer on Stackoverflow
Solution 7 - JavascriptcgpView Answer on Stackoverflow
Solution 8 - JavascriptCurtis YallopView Answer on Stackoverflow
Solution 9 - JavascriptModularView Answer on Stackoverflow
Solution 10 - JavascriptSlocombe9View Answer on Stackoverflow