Home >Web Front-end >JS Tutorial >How Can I Prevent Users from Losing Unsaved Form Data When Leaving a Page?
Preventing Unsaved Changes on Page Abandonment
When users navigate away from a page with unsaved form data, it's crucial to prompt them to confirm their intentions to avoid losing their work. To implement this:
Short but Limited Approach:
window.addEventListener("beforeunload", function (e) { e.returnValue = "Warning: Unsaved changes. Are you sure you want to leave?"; });
This approach, however, triggers the confirmation message even when form data is submitted, requiring a workaround.
Comprehensive Solution with Dirty Flag:
To prevent the confirmation message from appearing on irrelevant page leaves, use a "dirty" flag that indicates when form data has been changed.
const isDirty = () => false; window.addEventListener("beforeunload", function (e) { if (formSubmitting || !isDirty()) { return; } e.returnValue = "Warning: Unsaved changes. Are you sure you want to leave?"; });
Implement the isDirty method using:
Warning: Limited Browser Support
Note that custom confirmation messages are no longer supported in some browsers, such as Chrome 51 and later. Alternatives include displaying a generic dialog with "Leave" and "Stay" buttons.
The above is the detailed content of How Can I Prevent Users from Losing Unsaved Form Data When Leaving a Page?. For more information, please follow other related articles on the PHP Chinese website!