How to Stop a Page from Unloading (Navigating Away) in Js

Prevent a webpage from navigating away using 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?";
}

How do I stop a page from unloading with standardized JavaScript (Not `onbeforeunload`)

You can not prevent this entirely, however can notify the user via a popup that he should not reload. This is done with the onbeforeunload window event, best documented at MDN.

This will behave exactly like here on Stackoverflow, if you add some text to the answer textarea and than try to leave the page.

Prompting and preventing user from navigating away/closing a page

You need to implement window.onbeforeunload and return your message from it as a string:

window.onbeforeunload = function() {
if (theUserHasStartedEditing) {
return "You have started writing or editing a post."
}
}

There's an online demo here: https://web.archive.org/web/20210619174356/https://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo2.htm



Related Topics



Leave a reply



Submit