Files
KART-FRONT-NEXT/src/lib/auth-change.ts

36 lines
1.1 KiB
TypeScript

import { reportUrl } from "@/types/share";
// Set false to disable only cross-tab notifications and their listener.
const AUTH_CHANGE_SYNC_ENABLED = true;
const CHANNEL = "kart:auth-change";
let channel: BroadcastChannel | undefined;
function authChannel() {
if (!AUTH_CHANGE_SYNC_ENABLED || typeof BroadcastChannel === "undefined") return;
try {
return channel ??= new BroadcastChannel(CHANNEL);
} catch {
// Cross-tab sync is optional when the browser disallows messaging.
return undefined;
}
}
export function notifyAuthChange(path: string) {
authChannel()?.postMessage(path);
}
export function subscribeToAuthChanges() {
const listener = authChannel();
if (!listener) return;
listener.onmessage = (event: MessageEvent<unknown>) => {
const path = event.data === "/" || event.data === "/login"
? event.data : reportUrl(event.data);
// A full navigation discards this tab's cache/state without clearing the new cookie.
if (path) window.location.replace(path);
};
return () => {
listener.close();
channel = undefined;
};
}