/** * 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). */ (function () { var forms = document.querySelectorAll('form[data-beforeunload-guard]'); if (!forms.length) return; var dirty = false; for (var i = 0; i < forms.length; i++) { var form = forms[i]; form.addEventListener('input', function () { dirty = true; }); form.addEventListener('change', function () { dirty = true; }); form.addEventListener('submit', function () { dirty = false; }); } window.addEventListener('beforeunload', function (e) { if (dirty) { e.preventDefault(); } }); })();