send-channel-message
This package provide simple function that allow to pass messages to separate script in different browsing context and get back result data as a Promise using Channel Messaging API.
Motivation
If you just want to communicate with script in other window/iframe/worker, you can use postMessage function and onMessage event handler.
But if you want to communicate in Promise style, so thats a problem. And Channel Messaging API solves this problem using two-way channels with a port at each end.
Installation
Install the package to your project:
npm install --save send-channel-message
And then you can import the function:
-
If you used ES modules:
; -
If you used it in CommonJS environment (don’t forget to add
.default
to your import):var sendChannelMessage = default; -
Additionally it's also support a UMD build:
var sendChannelMessage = windowsendChannelMessagedefault;
Usage
Basically it's a function that takes 3 inputs and return a Promise:
const promise = ;
When Promise resolves it return object with response data:
promise;
Inputs
-
message - data to be sent to the other script.
-
target - a reference to the window/worker that will receive the
message
. -
origin - specifies what the origin of
target
must be for the event to be dispatched (default = "*").
*See postMessage syntax description.
Outputs
data
property of the MessageEvent
interface.
*See MessageEvent data description.
Example
You can create a module for communicating with some iFrame using send-channel-message
like this:
/* iframeCommunicator.js */;const target = documentcontentWindow;{return ;}{const message =type: 'INIT'initData;return ;}// ...;
And then use it for simple send requests and receive responses in API-like style:
/* index.js */;// ...iframeCommunicator;// ...
The iFrame script will look something like this:
/* iframe.js */window;
Tests
Simply clone the repo and run
npm install
npm test
License
MIT