Skip to content

Show an alert when leaving site with unsaved changes #2795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions client/modules/IDE/pages/IDEView.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,26 @@ function WarnIfUnsavedChanges() {

const currentLocation = useLocation();

// beforeunload handles closing or refreshing the window.
useEffect(() => {
const handleUnload = (e) => {
// See: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#browser_compatibility
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for adding this, this is great! It would definitely be helpful to have more of these references/comments throughout the codebase!

e.preventDefault();
e.returnValue = t('Nav.WarningUnsavedChanges');
};

if (hasUnsavedChanges) {
window.addEventListener('beforeunload', handleUnload);
} else {
window.removeEventListener('beforeunload', handleUnload);
}

return () => {
window.removeEventListener('beforeunload', handleUnload);
};
}, [t, hasUnsavedChanges]);

// Prompt handles internal navigation between pages.
return (
<Prompt
when={hasUnsavedChanges}
Expand Down