https://github.com/tborychowski/poster
2-way postMessage
https://github.com/tborychowski/poster
javascript postmessage
Last synced: about 1 year ago
JSON representation
2-way postMessage
- Host: GitHub
- URL: https://github.com/tborychowski/poster
- Owner: tborychowski
- License: gpl-3.0
- Created: 2017-06-07T13:47:20.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2018-06-13T13:38:34.000Z (about 8 years ago)
- Last Synced: 2025-02-14T03:23:30.756Z (over 1 year ago)
- Topics: javascript, postmessage
- Language: HTML
- Size: 18.6 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# poster
2-way postMessage
## API
#### initialisation
```js
/**
* Poster
* @param target - DOM node of the target:
* - if it's a parent app - target should be the iframe to which messages are sent
* - if initialisation is inside the iframe - the target would usually be the top/parent window
* @param onMessageReceivedCallback - function that will be called when a message is received FROM the target
*/
const poster = new Poster(target, onMessageReceivedCallback);
/**
* onMessageReceivedCallback
* @param actionName - or channel; any string will do
* @param params - can be a primitive, or a [serialisable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) object that will be passed along with the message
* @param responseCallback [optional] - if the received message expects a callback - this function should be called
*/
function onMessageReceivedCallback (actionName, params, responseCallback) { }
```
#### sending messages
```js
/**
* poster.send
* @param actionName - or channel; any string will do
* @param params - can be a primitive, or a [serialisable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) object that will be passed along with the message
* @param responseCallback [optional] - if a callback is needed - the passed function will be called, once the receiver responds to this message
*/
poster.send(actionName, params, responseCallback);
```
## Example usage
**index.html**
```js
const p = new Poster(document.getElementById('frame'), (action, params, cb) => {
console.log('parent: onmessage', action, params);
setTimeout(() => {
cb({ response: 'callback from parent' });
}, 1000);
});
p.send('parent-frame', { param: 'param one' }, msg => {
console.log('parent: callback message', msg);
});
```
**frame.html**
```js
const p = new Poster(window.top, (action, params, cb) => {
console.log('frame: onmessage', action, params);
setTimeout(() => {
cb({ response: 'callback from frame' });
}, 1000);
});
p.send('parent-frame', { param: 'param one' }, msg => {
console.log('parent: callback message', msg);
});
```