Skip to content

Add beforeunload event listener when a form is open #311

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
25 changes: 25 additions & 0 deletions src/pages/FormPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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%;`;
Expand Down