Transport for communication between iframe and parent window
npm install magic-transport
or
yarn add magic-transport
Insert the following code on the page where the iframe
is embeded (provider
page):
import {Provider} from 'magic-transport'
const id = 'UNIQ_ID'
const childOrigin = '*'
const sharedObject = {
hello: {
from: {
provider() {
return 'hello from provider'
}
}
}
}
const transport = new Provider({id, childOrigin, ...sharedObject})
transport.once('ready', async () => {
const consumerResult = await transport.consumer.hello.from.consumer()
console.log(consumerResult) // 'hello from provider'
transport.consumer.timeout((result) => {
console.log(result) // 'hello from consumer'
}, 1000)
transport.consumer.on('my_event', (result) => {
console.log(result) // {foo: 'bar'}
})
})
Insert the following code on the page loaded in the iframe
(consumer
page):
import {Consumer} from 'magic-transport'
const id = 'UNIQ_ID'
const parentOrigin = '*'
const sharedObject = {
hello: {
from: {
consumer() {
return transport.provider.hello.from.provider()
}
}
},
timeout(callback, timeout) {
setTimeout(() => {
callback('hello from consumer')
}, timeout)
}
}
const transport = new Consumer({id, parentOrigin, ...sharedObject})
transport.once('ready', () => {
transport.consumer.emit('my_event', {foo: 'bar'})
})
Both Consumer
and Provider
interfaces can return any values, which will be resolved as a Promise. Passed callbacks will be called as well.
import {Provider} from 'magic-transport'
const id = 'UNIQ_ID'
const childOrigin = '*'
const sharedObject = {
hello: {
from: {
provider: function () {
return 'hello from provider'
}
}
}
}
const iframe = document.createElement('iframe')
iframe.src = 'https://site.app/embed'
document.body.appendChild(iframe)
const transport = new Provider({
id,
childOrigin,
connectedWindow: iframe.contentWindow,
...sharedObject
});
Currently we only have the API which you can check here.
After you clone the repo you just need to run yarn
's default command to install and build the packages
yarn
We have a test suite consisting of a bunch of unit tests to verify utils keep working as expected. Test suit is run in CI on every commit.
To run the tests
yarn test
To run the tests in watch mode
yarn test:watch
To run linting the codebase
yarn lint
To check typings
yarn typecheck
To check bundle size
yarn sizecheck
Please open an issue if you have any questions or concerns.
MIT