iframe-message-bridge
v1.1.1
Published
[![Version npm](https://img.shields.io/npm/v/iframe-message-bridge.svg?style=flat-square)](https://www.npmjs.com/package/iframe-message-bridge)
Downloads
63
Readme
iframe-message-bridge
A small tool for communicating between window and iframe.
Usage
Basic
npm install iframe-message-bridge
Example
// top
import { Bridge } from 'iframe-bridge-promised';
const iframe = document.getElementById('iframe');
const bridge = new Bridge(iframe.contentWindow);
bridge.on('ready', () => {
// basic
bridge.post('say');
// async
bridge.post('delay').then(() => {
console.log('complete');
});
// with payload
bridge
.post('greet', {
name: 'John',
})
.then((response) => {
// Vivian
console.log(response.name);
});
});
// iframe
import { Bridge } from 'iframe-bridge-promised';
const bridge = new Bridge(window.parent);
bridge.post('ready');
bridge.on('say', () => {
console.log('Hello');
});
bridge.on('delay', () => {
return Promise((resolve) => {
setTimeout(resolve, 2000);
});
});
bridge.on('greet', (payload) => {
console.log(payload.name); // John
return Promise((resolve) => {
setTimeout(() => {
resolve({
name: 'Vivian',
});
}, 2000);
});
});
Options
targetWindow required
The target window object.
prefix default: 'iframe-message-bridge'
The prefix of event name. only used internally to prevent irrelevant postMessage event.
timeout default: 20000
The timeout of post event promise.
targetOrigin default: '*'
see postMessage
transfer default: undefined
see postMessage