Skip to content

Commit d961e49

Browse files
authored
Merge pull request #2795 from lindapaiste/fix/beforeunload
Show an alert when leaving site with unsaved changes
2 parents 3cbf4c5 + fb2d231 commit d961e49

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

client/modules/IDE/pages/IDEView.jsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,26 @@ function WarnIfUnsavedChanges() {
4848

4949
const currentLocation = useLocation();
5050

51+
// beforeunload handles closing or refreshing the window.
52+
useEffect(() => {
53+
const handleUnload = (e) => {
54+
// See: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#browser_compatibility
55+
e.preventDefault();
56+
e.returnValue = t('Nav.WarningUnsavedChanges');
57+
};
58+
59+
if (hasUnsavedChanges) {
60+
window.addEventListener('beforeunload', handleUnload);
61+
} else {
62+
window.removeEventListener('beforeunload', handleUnload);
63+
}
64+
65+
return () => {
66+
window.removeEventListener('beforeunload', handleUnload);
67+
};
68+
}, [t, hasUnsavedChanges]);
69+
70+
// Prompt handles internal navigation between pages.
5171
return (
5272
<Prompt
5373
when={hasUnsavedChanges}

0 commit comments

Comments
 (0)