实现说明
演示用的数据放在这几个模块级绑定中:dirty、form。
使用要点
document、window只存在于浏览器——Node 运行时没有现成的垫片。- 守卫
!dirty命中后立刻用提前的return结束这一轮。 - 每一步打印都带着自己的标签:
guard armed, dirty =。
常见问题
「beforeunload 拦截未保存的表单改动」能在裸 Node.js 里跑吗?
不能——它用到 document、window。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。
核心语句
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; });
代码示例
// 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);