message-channel
request and response abstraction for message channel
The best communication method between an iframe and the main frame is through Channel messaging API.
TLDR
Use this library for fast and performant communication between frames which uses message channel api underneath the hood.
why do i need it ?
let's say we want to have few iframes which need to communicate with the main frame.
usualy we'll need to:
- Listen to post messages from the main frame.
- Create a message channel from the iframe side.
- Send a post message with one of the ports to the main frame.
- Get the message from the iframe and register a callback to messages from the channel.
- Be able to fit the main frame replies to the requests from the iframe.
with message-channel
// on the main frame; // the listener will call the onMessage callback everytime a connection is being established. const handleMessage = ; ;
// on the iframe; // Establish a connection with the main frame and send messages.const send = await ; ; // 'hello world'
Installation
use a scipt tag and import the bundle
<!-- add this on the main frame -->
<!-- add this on the iframe -->
you can also use npm
npm i --save message-channel
or yarn
yarn add message-channel
basic usage
scope - A scope is way to differentiate between two or more message-channels in the same application. (it has to be the same on both listener and connect)
methods
string
, options: object
): reply: string
connectMessageChannel(scope: - targetOrigin =
string
(target origin for the connection post message) = '*', - connectionMaxTimeout:
number
(ms) = 200 - messageMaxTimeout:
number
(ms) = 6000
string
, messageHandler: function
): void
listenerMessageChannel(scope: ;
important note!: The event you'll get on the onMessage
callback is a mirror of the messageEvent type. The reason for not sending the "real" event, is that we add an id to every message and we want to strip the id from the data.
stop the listener
If you want to stop the listener, just call the stop function which returns from the call to the listener.
const stop = ; ; // The listener won't work.