@livechat/postmessage
v0.3.5
Published
A library which makes [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) communication easier. It's responsible for:
Downloads
4,138
Keywords
Readme
@livechat/postmessenger
A library which makes postMessage
communication easier. It's responsible for:
- establishing a connection between a parent page and a child iframe,
- allowing promisified remote procedure calls,
- allowing events to be dispatched to the listener on the other side.
It's using a custom protocol for a communication - it's using a distinct shape of passed frames. The protocol was designed with different frame types in mind (currently handshake, response, call & emit). Given global nature of window.postMessage
communication, it annotates all sent frames with:
- "unique" fingerprint (namespaced string),
- owner ID (allows multiple copies of the library to coexist on a single page),
- instance ID (allows multiple instances to be created on a single page).
Terminology
Handshake
Handshake is the point in time when we know that the connection has been established and it's safe to send data between parties.
Both sides of the communication receive a promise object which resolves after the so-called handshake. It's the point in time when we know that the connection has been established and it's safe to send data to the "other side".
Model
Object consisting of data & methods given to the initialization function.
Data (plain values) are being sent to the "other side" and are given to the consumer on the "other side" when initialization promise resolves.
Methods are being registered within instance and can be called remotely by the instance existing on the other side of the communication using instance.call('methodName', ...args)
.
Types
type Api = {
call: (method: string, ...args: any[]) => Promise<any>,
emit: (event: string, data: any) => void,
off: (event: string, callback: (...args: any[]) => any) => void,
on: (event: string, callback: (...args: any[]) => any) => void,
once: (event: string, callback: (...args: any[]) => any) => void,
}
type Model = { [key: string]: string | number | (...args: any[]) => any }
type Destroy = () => void
type IframeInstance = {
destroy: Destroy,
frame: HTMLIFrameElement,
promise: Promise<Api & {
destroy: Destroy,
frame: HTMLIFrameElement,
data: { [key: string]: string | number }
}>
}
type ParentInstance = {
promise: Promise<Api & {
data: { [key: string]: string | number }
}>
}
API
createIframe
function createIframe(
{
container,
url,
targetOrigin,
handshakeRetry,
}: {
container: string
url: string
targetOrigin?: string
handshakeRetry?: { interval?: number; count?: number }
},
model?: Model,
): IframeInstance
connectToParent
function connectToParent(
model?: Model,
options?: { handshakeTimeout?: number },
): IframeInstance