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.

TypescriptData Integrity

Code

typescriptsnippet
16 lines
// 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, window are not available in Node.
  • The guard !dirty ends the flow early via return when 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

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.