import { MessageBroker, MessageBrokerListener, MessageData } from '../../types'; const namespace = 'raydiant'; // The post message broker is used to send and receive messages when running // in a browser/iframe environment. export function createPostMessageBroker( windowId: string, window: Window ): MessageBroker { const brokerListeners = new Set(); window.addEventListener('message', (event) => { if (event.source !== window.parent) { // Only handle events that come from the parent window. return; } // Ignore messages that don't start with the message prefix. if (isValidData(event.data)) { let type = ''; let payload: unknown; if (typeof event.data === 'string') { ({ type, payload } = deserializeMessage(event.data)); } else { ({ type, payload } = event.data); } if (!type) { // Only handle events that have a type. console.warn(`Invalid message received from parent '${event.data}'`); return; } // Notify listeners of message. for (const listener of brokerListeners) { listener(type, payload); } } }); return { sendMessage(type: string, payload: unknown) { // Send message to parent window. window.parent.postMessage(serializeMessage(windowId, type, payload), '*'); }, registerListener(listener) { // Register listener. brokerListeners.add(listener); // Return unsubscribe function. return () => { brokerListeners.delete(listener); }; }, }; } // Check if the event data is a valid message. Messages are sent as strings or objects. // Strings are in the format of 'raydiant:{ type: string, payload: unknown }'. while objects // are in the format of { namespace: 'raydiant', type: string, payload: unknown }. const isValidData = (data: unknown): data is MessageData => { if (typeof data === 'string') { return data.startsWith(`${namespace}:`); } if (typeof data === 'object') { return ( !!data && 'namespace' in data && typeof data['namespace'] === 'string' && data['namespace'] === namespace ); } return false; }; const serializeMessage = (windowId: string, type: string, payload: unknown) => { return `${namespace}:${JSON.stringify({ windowId, type, payload })}`; }; const deserializeMessage = (message: string) => { let type = ''; let payload: unknown; const json = message.replace('raydiant:', ''); try { // Messages are sent as json in the format of { type: string, payload: unknown }. ({ type, payload } = JSON.parse(json)); } catch (err) { // Not a valid message, return empty type and payload. } return { type, payload }; };