From fd4828634599e12289b40be348b6acc677b7a9f5 Mon Sep 17 00:00:00 2001 From: Bluenix Date: Mon, 26 Jul 2021 00:46:01 +0200 Subject: [PATCH] Add beforeunload event listener when a form is open This will make the browser prompt the user before they try to reload or close the page if they have a form open. --- src/pages/FormPage.tsx | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/pages/FormPage.tsx b/src/pages/FormPage.tsx index d7dfd4b1..494ec41d 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%;`;