Skip to content

Commit

Permalink
feat(sdk): [wip] send config from SDK to chat
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremyckahn committed Oct 17, 2023
1 parent bc53e4a commit c439283
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
30 changes: 30 additions & 0 deletions sdk/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ enum ChatEmbedAttributes {
ROOM_NAME = 'room',
}

const pollInterval = 250

class ChatEmbed extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({ mode: 'open' })
Expand All @@ -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)
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/Bootstrap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
Expand Down

0 comments on commit c439283

Please sign in to comment.