From ebd038c077e85937a16c8c445e33fc00cc9b26cb Mon Sep 17 00:00:00 2001 From: Carson Full Date: Sat, 12 Oct 2024 15:07:22 -0500 Subject: [PATCH] Broadcast impersonation changes --- src/api/client/ImpersonationContext.tsx | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/api/client/ImpersonationContext.tsx b/src/api/client/ImpersonationContext.tsx index 3663ebca20..510b57350a 100644 --- a/src/api/client/ImpersonationContext.tsx +++ b/src/api/client/ImpersonationContext.tsx @@ -28,6 +28,11 @@ export const ImpersonationProvider = ({ children, initial, }: ChildrenProp & { initial?: Impersonation | null }) => { + const [broadcast] = useState(() => + typeof BroadcastChannel !== 'undefined' + ? new BroadcastChannel('impersonation') + : undefined + ); const [impersonation, setImpersonation] = useState(() => { if (initial !== undefined) { return initial ?? undefined; @@ -41,6 +46,7 @@ export const ImpersonationProvider = ({ : undefined; next = next && Object.keys(next).length === 0 ? undefined : next; setImpersonation(next); + broadcast?.postMessage(next); if (!next) { Cookies.remove('impersonation'); return; @@ -50,7 +56,7 @@ export const ImpersonationProvider = ({ sameSite: 'strict', }); }, - [setImpersonation] + [setImpersonation, broadcast] ); const value = useMemo( () => ({ @@ -61,6 +67,21 @@ export const ImpersonationProvider = ({ [impersonation, set] ); + useEffect(() => { + if (!broadcast) { + return; + } + const listener = (event: MessageEvent) => { + setImpersonation(event.data); + }; + broadcast.addEventListener('message', listener); + return () => { + broadcast.removeEventListener('message', listener); + broadcast.close(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + // Expose devtools API const latest = useLatest(value); useEffect(() => {