📮 Streaming iterables over `window.postMessage`
MIT License
Streaming iterables over
window.postMessage
It provides the two parts of a duplex stream: a source stream and a sink stream that can be used together to stream data over window.postMessage
.
npm install it-postmsg
To use it-postmsg
you need two window objects. One of the window objects has the data, the other wants the data. Under the hood, it-postmsg
uses postmsg-rpc
. If you're not familiar with it, it's a good idea to read up on how it works before continuing!
In the first window (the one that has the data):
const PostMessage = require('it-postmsg')
const pipe = require('it-pipe')
pipe(
[/* your data */],
PostMessage.sink('<stream ID>', {/* options passed to postmsg-rpc expose */})
)
In the second window (the one that wants the data):
const PostMessage = require('it-postmsg')
const pipe = require('it-pipe')
pipe(
PostMessage.source('<stream ID>', {/* options passed to postmsg-rpc caller */}),
async function logSink (source) {
for await (const chunk of source) {
console.log(chunk)
}
}
)
PostMessage.sink
, which exposes a function called <stream ID>_next
& returns a sink
PostMessage.source
, which creates a caller function for "read" & returns a source
pipe(...)
pipeline starts the flow of data from the PostMessage.source
streamPostMessage.source
stream, it calls the exposed <stream ID>_next
functionPostMessage.sink
stream in the window that has the data to retrieve the next item from the data array and return it all the way back to logSink
in the window that wants the dataSee the example for complete code.
To build and run the example, run the following in your terminal:
git clone https://github.com/alanshaw/it-postmsg.git
cd it-postmsg
npm install
npm run example
Then open your browser at http://localhost:3000
PostMessage.sink(id, options)
Creates a new sink for writing data over postMessage
.
id
- a unique ID for the stream. postmsg-rpc
uses it to expose functions that PostMessage.source
can read from.options
- options passed directly to postmsg-rpc
expose
, see docs here
PostMessage.source(id, options)
Creates a new source for reading data over postMessage
.
id
- a unique ID for the stream, note that it should be the same ID used in PostMessage.sink
options
- options passed directly to postmsg-rpc
caller
, see docs here
Feel free to dive in! Open an issue or submit PRs.
MIT © Alan Shaw