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
Internal/Modules/Cjs/Loader.Js:582 Throw Err
Which Browsers Support Import and Export Syntax for Ecmascript 6
Check If Jquery Has Been Loaded, Then Load It If False
How to Stop Babel from Transpiling 'This' to 'Undefined' (And Inserting "Use Strict")
Array.Length Is Zero, But the Array Has Elements in It
Mobile Safari: JavaScript Focus() Method on Inputfield Only Works with Click
How to Remove a Key from a JavaScript Object
What Is Difference Between Axios and Fetch
How to Rotate a 3D Object on Axis Three.Js
Angular 2: Import External Js File into Component
Getting Binary Content in Node.Js Using Request
JavaScript Audio Play on Click
Npm Install Cannot Find Module 'Semver'