post-messenger
A simple wrapper of
window.postMessage
for cross-document communication with each other.一个简单的
window.postMessage
封装,用于跨文档的双向数据通信。
Feature
- Simple wrapper for
postMessage
. - Use it just like
event emitter
. - Event channel
namespace
supported.
Install
npm i --save post-messenger
or import it by script
in HTML, then get PostMessenger
on window.
Usage
- In
parent
document.
; // connect to iframeconst pm = ; const listener = { console;} // listen the messagespm; pm;
- In
iframe
document.
; // connect to parentconst pm = ; const listener = { console;} // send messagespm; pm;
Full example can be found here, and code here.
API
There is only one function named PostMessenger
, you can get the instance by:
// projectId: the theme of communication.// targetDocument: the document which you want to connect and communicate.const pm = ;
The instance has 4 apis.
- pm.once(channel, listener)
Add a message listener on channel for once.
- pm.on(channel, listener)
Add a message listener on channel.
- pm.off([channel, listener])
Remove listener, if channel
and listener
are all undefined
, remove all.
- pm.send(channel, message)
Send a message to the channel.
Scenes
The
window.postMessage()
method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
The communicate target can be:
- Window.open
- Window.opener
- HTMLIFrameElement.contentWindow
- Window.parent
- Window.frames
Reference here.
License
MIT@hustcc.