diff --git a/src/components/Hyperchat.svelte b/src/components/Hyperchat.svelte index 2871524..2ed9079 100644 --- a/src/components/Hyperchat.svelte +++ b/src/components/Hyperchat.svelte @@ -19,9 +19,18 @@ Browser, Theme, YoutubeEmojiRenderMode, - chatUserActionsItems + chatUserActionsItems, + + ChatReportUserOptions + } from '../ts/chat-constants'; - import { isAllEmoji, isChatMessage, isPrivileged, responseIsAction } from '../ts/chat-utils'; + import { + isAllEmoji, + isChatMessage, + isPrivileged, + responseIsAction, + useReconnect + } from '../ts/chat-utils'; import Button from 'smelte/src/components/Button'; import { theme, @@ -281,24 +290,31 @@ frameId: parseInt(paramsFrameId) }; - $port = chrome.runtime.connect({ name: JSON.stringify(frameInfo) }); + let hasRun = false; + $port = useReconnect(() => { + const port = chrome.runtime.connect({ + name: JSON.stringify(frameInfo) + }) as Chat.Port; - $port?.onMessage.addListener(onPortMessage); + port.onMessage.addListener(onPortMessage); - $port?.postMessage({ - type: 'registerClient', - getInitialData: true - }); - $port?.postMessage({ - type: 'getTheme' - }); + port.postMessage({ + type: 'registerClient', + getInitialData: true + }); - // service worker gets shut down after 30s of not receiving events - const interval = setInterval(() => $port?.postMessage({ - type: 'ping' - }), 15_000); + if (!hasRun) { + port.postMessage({ + type: 'getTheme' + }); + } + + hasRun = true; + + return port; + }); - return () => clearInterval(interval); + return () => $port?.destroy && $port?.destroy(); }; onMount(onLoad); diff --git a/src/ts/chat-utils.ts b/src/ts/chat-utils.ts index df74ee2..7f34749 100644 --- a/src/ts/chat-utils.ts +++ b/src/ts/chat-utils.ts @@ -67,3 +67,25 @@ export const checkInjected = (error: string): boolean => { } return false; }; + +export const useReconnect = (connect: () => T): T & { destroy: () => void } => { + let actualPort = connect(); + const onDisconnect = (): void => { + actualPort = connect(); + actualPort.onDisconnect.addListener(onDisconnect); + }; + actualPort.onDisconnect.addListener(onDisconnect); + + return { + ...actualPort, + get name() { return actualPort.name; }, + get disconnect() { return actualPort.disconnect; }, + get postMessage() { return actualPort.postMessage; }, + get onMessage() { return actualPort.onMessage; }, + get onDisconnect() { return actualPort.onDisconnect; }, + destroy: () => { + actualPort.onDisconnect.removeListener(onDisconnect); + actualPort.disconnect(); + } + }; +}; diff --git a/src/ts/typings/chat.d.ts b/src/ts/typings/chat.d.ts index 5b32380..44f4382 100644 --- a/src/ts/typings/chat.d.ts +++ b/src/ts/typings/chat.d.ts @@ -154,6 +154,7 @@ declare namespace Chat { callback: (message: BackgroundResponse, port: Port) => void ) => void; }; + destroy?: () => void; }; interface Interceptor {