Files
community-rule/app/hooks/useBeforeUnloadGuard.ts
T

34 lines
910 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect } from "react";
/**
* Attach the browsers native leave-site prompt while `enabled` is true.
*
* Modern browsers ignore custom copy; this only blocks accidental tab or
* window close. No-ops during SSR and when `enabled` is false so clean
* sessions never register a listener.
*
* @param enabled Whether unsaved work would be lost on unload.
*
* @example
* useBeforeUnloadGuard(isWizardSessionDirty());
*/
export function useBeforeUnloadGuard(enabled: boolean): void {
useEffect(() => {
if (!enabled || typeof window === "undefined") {
return;
}
const onBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = "";
};
window.addEventListener("beforeunload", onBeforeUnload);
return () => {
window.removeEventListener("beforeunload", onBeforeUnload);
};
}, [enabled]);
}