Skip to content

Commit

Permalink
Add "beforeunload" event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
arnautov-anton committed Jul 18, 2023
1 parent 0208cca commit a9fc50b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
11 changes: 10 additions & 1 deletion sample-apps/react/react-dogfood/components/MeetingUI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();
Expand Down
1 change: 1 addition & 0 deletions sample-apps/react/react-dogfood/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './useChatClient';
export * from './useWatchChannel';
export * from './useKeyboardShortcuts';
export * from './useBeforeUnload';
18 changes: 18 additions & 0 deletions sample-apps/react/react-dogfood/hooks/useBeforeUnload.ts
Original file line number Diff line number Diff line change
@@ -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]);
};

0 comments on commit a9fc50b

Please sign in to comment.