From ff7329eaac866e9232ab4e501a07861a3c545101 Mon Sep 17 00:00:00 2001 From: Anton Arnautov Date: Tue, 27 Jun 2023 20:59:45 +0200 Subject: [PATCH] Add "beforeunload" event handler --- .../react-dogfood/components/MeetingUI.tsx | 11 ++++++++++- sample-apps/react/react-dogfood/hooks/index.ts | 1 + .../react-dogfood/hooks/useBeforeUnload.ts | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 sample-apps/react/react-dogfood/hooks/useBeforeUnload.ts diff --git a/sample-apps/react/react-dogfood/components/MeetingUI.tsx b/sample-apps/react/react-dogfood/components/MeetingUI.tsx index 25bb4d1363..f7768b480d 100644 --- a/sample-apps/react/react-dogfood/components/MeetingUI.tsx +++ b/sample-apps/react/react-dogfood/components/MeetingUI.tsx @@ -33,7 +33,11 @@ import { UnreadCountBadge, } from '.'; import { ActiveCallHeader } from './ActiveCallHeader'; -import { useKeyboardShortcuts, useWatchChannel } from '../hooks'; +import { + useBeforeUnload, + useKeyboardShortcuts, + useWatchChannel, +} from '../hooks'; import { DEFAULT_LAYOUT, getLayoutSettings, LayoutMap } from './LayoutSelector'; import { Stage } from './Stage'; import { ToggleParticipantListButton } from './ToggleParticipantListButton'; @@ -107,6 +111,11 @@ export const MeetingUI = ({ chatClient, enablePreview }: MeetingUIProps) => { } }, [router]); + useBeforeUnload( + callState === CallingState.JOINED, + 'Call in progress, are you sure you want to leave?', + ); + useEffect(() => { if (callState === CallingState.LEFT) { void onLeave(); diff --git a/sample-apps/react/react-dogfood/hooks/index.ts b/sample-apps/react/react-dogfood/hooks/index.ts index ccb068d61e..8f049fbeb7 100644 --- a/sample-apps/react/react-dogfood/hooks/index.ts +++ b/sample-apps/react/react-dogfood/hooks/index.ts @@ -1,3 +1,4 @@ export * from './useChatClient'; export * from './useWatchChannel'; export * from './useKeyboardShortcuts'; +export * from './useBeforeUnload'; diff --git a/sample-apps/react/react-dogfood/hooks/useBeforeUnload.ts b/sample-apps/react/react-dogfood/hooks/useBeforeUnload.ts new file mode 100644 index 0000000000..1616ab6e47 --- /dev/null +++ b/sample-apps/react/react-dogfood/hooks/useBeforeUnload.ts @@ -0,0 +1,18 @@ +import { useEffect } from 'react'; + +export const useBeforeUnload = (enabled: boolean, message: string) => { + useEffect(() => { + if (!enabled) return; + + const handleBeforeUnload = (e: Event) => { + e.preventDefault(); // <- this does not work even though it's preffered way + + // window.confirm does not work to display custom message + // @ts-expect-error + return (e.returnValue = message); + }; + + window.addEventListener('beforeunload', handleBeforeUnload); + return () => window.removeEventListener('beforeunload', handleBeforeUnload); + }, [enabled, message]); +};