message-event-channel
An event driven fault tolerant library for communicating between contexts using MessageChannel.
Features
- Subscribe to and broadcast events
- Send and receive JSON
- Make requests that return a promise
Installation
Using npm:
npm install message-event-channel --save
Using cdn:
<script src="https://unpkg.com/message-event-channel/dist/message-event-channel.umd.js"></script>
Including
import { ClientConnection } from 'message-event-channel';
const connection = new ClientConnection();
or
const mc = require('message-event-channel');
const connection = new mc.ClientConnection();
or
<script src="https://unpkg.com/message-event-channel/dist/message-event-channel.umd.js"></script>
<script>
const connection = new mc.ClientConnection();
</script>
Usage
Events
/parent.html
import { ServerConnection } from 'message-event-channel';
const frame = document.querySelector('iframe');
const connection = new ServerConnection(frame);
connection.emit('my-event', {hello: 'world'});
frame.src = "./frame.html";
/frame.html
import { ClientConnection } from 'message-event-channel';
const connection = new ClientConnection();
connection.on('my-event', (payload)=>{
console.log(payload)
});
Request
/parent.html
import { ServerConnection } from 'message-event-channel';
const connection = new ServerConnection(frame);
connection.request('some-data')
.then(payload => {
console.log(payload)
})
frame.src = "./frame.html";
/frame.html
import { ClientConnection } from 'message-event-channel';
const connection = new ClientConnection();
connection.on('some-payload', (payload, resolve, reject)=>{
resolve({hello: 'world'})
});
Emit to all
/parent.html
import { Operator } from 'message-event-channel';
const operator = new Operator();
const connection1 = operator.connect(frame1);
const connection2 = operator.connect(frame2);
const connection3 = operator.connect(frame3);
operator.emit('send-to-all');
Close connection
/parent.html
import { ServerConnection } from 'message-event-channel';
const connection = new ServerConnection(frame);
connection.close();
Options
{
targetOrigin: '*'
onload: true,
timeout: 2000,
debug: false,
connectionTimeout: 2000
clientInitiates: false
}