Beforeunload Guards Unsaved Form Edits
Wire beforeunload to unsaved form state so the browser asks before discarding edits, using preventDefault plus returnValue per current guidance.
Code
// Registering beforeunload asks the browser to confirm navigation while the
// form still has unsaved edits. The prompt text is chosen by the browser —
// the handler only opts in.
let dirty = false;
const form = document.querySelector<HTMLFormElement>('#profile-form');
form?.addEventListener('input', () => { dirty = true; });
form?.addEventListener('submit', () => { dirty = false; }); // submit resets, redirect is silent
window.addEventListener('beforeunload', (event) => {
if (!dirty) return;
event.preventDefault(); // cancel the silent navigation
event.returnValue = ''; // legacy engines read this instead
});
console.log('guard armed, dirty =', dirty);Under the hood
All the work happens over top-level bindings: dirty, form.
Watch out for
- Setup is empty: the platform already ships every API used.
- A browser is the runtime here:
document,windoware not available in Node. - The guard
!dirtyends the flow early viareturnwhen its condition holds.
Putting it to use
Output lines are prefixed (guard armed, dirty =), which makes it easy to spot each step’s effect.
Core lines
form?.addEventListener('submit', () => { dirty = false; }); // submit resets, redirect is silent
window.addEventListener('beforeunload', (event) => {
if (!dirty) return;
event.preventDefault(); // cancel the silent navigation
event.returnValue = ''; // legacy engines read this instead
});
form?.addEventListener('input', () => { dirty = true; });
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does Beforeunload Guards Unsaved Form Edits run in plain Node.js?
- No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.