UNPKG

@design.estate/dees-comms

Version:

A communications module for enabling DOM-based messaging and synchronization across browser tabs and workers.

70 lines (62 loc) 2.19 kB
import * as plugins from './dees-comms.plugins.js'; let BroadcastChannel = globalThis.BroadcastChannel; if (!BroadcastChannel) { BroadcastChannel = plugins.BroadCastChannelPolyfill as any; } /** * a comm class for client side communication between workers and tabs. */ export class DeesComms { private broadcastChannel = new BroadcastChannel('dees-comms'); // sending messages public typedrouter = new plugins.typedrequest.TypedRouter(); public typedtarget = new plugins.typedrequest.TypedTarget({ postMethodWithTypedRouter: async (messageArg) => { this.postMessage(messageArg); }, typedRouterRef: this.typedrouter, }); // receiving messages constructor() { this.broadcastChannel.onmessage = async (eventArg) => { const message = (eventArg as any).method ? eventArg : eventArg.data; console.log(JSON.stringify(message)); // Skip hooks for broadcast-received messages to prevent infinite loops // when traffic logging hooks are set up globally const response = await this.typedrouter.routeAndAddResponse(message, { skipHooks: true }); if (response && !response.error) { this.postMessage(response); } else { // console.log(response); } }; } /** * creates a typedrequest with this classes postMessage as postMethod */ public createTypedRequest<T extends plugins.typedrequestInterfaces.ITypedRequest>( methodName: T['method'] ): plugins.typedrequest.TypedRequest<T> { const typedrequest = new plugins.typedrequest.TypedRequest(this.typedtarget, methodName); return typedrequest; } /** * posts a typedrequestmessage */ public async postMessage<T = plugins.typedrequestInterfaces.ITypedRequest>( messageArg: T ): Promise<void> { this.broadcastChannel.postMessage(messageArg); } /** * subscribe to messages */ public async createTypedHandler<T extends plugins.typedrequestInterfaces.ITypedRequest>( methodArg: T['method'], handlerFunction: plugins.typedrequest.THandlerFunction<T> ) { this.typedrouter.addTypedHandler( new plugins.typedrequest.TypedHandler<T>(methodArg, handlerFunction) ); } }