/** * Beforeunload guard — prompts the user before navigating away from unsaved changes. * * Attach to any form with a data-beforeunload-guard attribute. * No effect when JavaScript is unavailable (form posts normally). */ (() => { const forms = document.querySelectorAll('form[data-beforeunload-guard]'); if (!forms.length) return; let dirty = false; for (const form of forms) { form.addEventListener('input', () => { dirty = true; }); form.addEventListener('change', () => { dirty = true; }); form.addEventListener('submit', () => { dirty = false; }); } window.addEventListener('beforeunload', (e) => { if (dirty) { e.preventDefault(); } }); })();