From c4392835fd9902e0ad1754a57eb1c973c6c23366 Mon Sep 17 00:00:00 2001 From: Jeremy Kahn Date: Tue, 17 Oct 2023 09:43:02 -0500 Subject: [PATCH] feat(sdk): [wip] send config from SDK to chat --- sdk/sdk.ts | 30 ++++++++++++++++++++++++++++++ src/Bootstrap.tsx | 10 +++++----- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/sdk/sdk.ts b/sdk/sdk.ts index 65ca4b131..8da17ed38 100644 --- a/sdk/sdk.ts +++ b/sdk/sdk.ts @@ -18,6 +18,8 @@ enum ChatEmbedAttributes { ROOM_NAME = 'room', } +const pollInterval = 250 + class ChatEmbed extends HTMLElement { connectedCallback() { const shadow = this.attachShadow({ mode: 'open' }) @@ -44,6 +46,34 @@ class ChatEmbed extends HTMLElement { iframe.setAttribute('allow', iframeFeatureAllowList.join(';')) shadow.appendChild(iframe) + this.sendConfigToChat(iframe, rootUrl) + } + + private async sendConfigToChat(chat: HTMLIFrameElement, rootUrl: string) { + let timer: NodeJS.Timer + const { origin: rootUrlOrigin } = new URL(rootUrl) + + // FIXME: Use types for posted data + const handleMessageReceived = (event: MessageEvent) => { + if (rootUrlOrigin !== event.origin) return + + if (event.data?.name === 'configReceived') { + clearInterval(timer) + window.removeEventListener('message', handleMessageReceived) + } + } + + window.addEventListener('message', handleMessageReceived) + + timer = setInterval(() => { + chat.contentWindow?.postMessage( + { + name: 'config', + payload: {}, + }, + rootUrlOrigin + ) + }, pollInterval) } } diff --git a/src/Bootstrap.tsx b/src/Bootstrap.tsx index 8e5c28923..1bd3726e3 100644 --- a/src/Bootstrap.tsx +++ b/src/Bootstrap.tsx @@ -38,14 +38,14 @@ const waitForConfig = () => { setTimeout(reject, configWaitTimeout) + const { origin: parentFrameOrigin } = new URL(document.referrer) + window.addEventListener('message', (event: MessageEvent) => { - // FIXME: Make this work - //if (event.origin !== window.location.origin) return + if (event.origin !== parentFrameOrigin) return + // FIXME: Use types for posted data if (event.data?.name === 'config') { - console.log('got config') - // FIXME: Use a specific origin here - window.postMessage({ name: 'receivedConfig' }, '*') + window.parent.postMessage({ name: 'configReceived' }, parentFrameOrigin) resolve(event.data.payload) } })