aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Bluenix <[email protected]>2021-07-26 00:46:01 +0200
committerGravatar Bluenix <[email protected]>2021-07-26 22:46:55 +0200
commitfd4828634599e12289b40be348b6acc677b7a9f5 (patch)
tree18ae1e27ac3abbe9e6c8c24f63d47cda11bbbc32
parentSupport Line Breaks In Submitted Text (diff)
Add beforeunload event listener when a form is openbeforeunload-warning
This will make the browser prompt the user before they try to reload or close the page if they have a form open.
-rw-r--r--src/pages/FormPage.tsx25
1 files changed, 25 insertions, 0 deletions
diff --git a/src/pages/FormPage.tsx b/src/pages/FormPage.tsx
index d7dfd4b..494ec41 100644
--- a/src/pages/FormPage.tsx
+++ b/src/pages/FormPage.tsx
@@ -156,6 +156,31 @@ function FormPage(): JSX.Element {
});
}, []);
+ // This will prompt the user before they try to exit the page
+ const cancelUnload = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ // Not all browsers listen to preventDefault
+ event.returnValue = "";
+ return "";
+ };
+
+ useEffect(() => {
+ window.onbeforeunload = cancelUnload;
+
+ // The function we return is called when the page is unloaded
+ return () => {
+ window.onbeforeunload = null;
+ };
+ }, []);
+
+ useEffect(() => {
+ if (sent) {
+ window.onbeforeunload = null;
+ } else {
+ window.onbeforeunload = cancelUnload;
+ }
+ }, [sent]);
+
if (form && sent) {
const thanksStyle = css`font-family: "Uni Sans", "Hind", "Arial", sans-serif; margin-top: 15.5rem;`;
const divStyle = css`width: 80%;`;