Skip to content

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.

License

barkadron/send-channel-message

Repository files navigation

send-channel-message

npm version build status test coverage license minified size downloads

known vulnerabilities dependency status dev-dependency status

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:

    import sendChannelMessage from 'send-channel-message';
  • If you used it in CommonJS environment (don’t forget to add .default to your import):

    var sendChannelMessage = require('send-channel-message').default;
  • Additionally it's also support a UMD build:

    var sendChannelMessage = window.sendChannelMessage.default;

Usage

Basically it's a function that takes 3 inputs and return a Promise:

const promise = sendChannelMessage(message, target, origin);

When Promise resolves it return object with response data:

promise.then( (data) => {
    console.log(data);
});

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 */

import sendChannelMessage from 'send-channel-message';

const target = document.getElementById('someIframe').contentWindow;

function sendMessageToIframe(message) {
    return sendChannelMessage(message, target);
}

export default {
    initialize: (initData) => {
        const message = {
            type: 'INIT',
            initData
        };
        return sendMessageToIframe(message);
    },
    // ...
};

And then use it for simple send requests and receive responses in API-like style:

/* index.js */

import iframeCommunicator from './iframeCommunicator';

// ...

iframeCommunicator.initialize('very important data')
    .then( (data) => {
        console.log('Received init response:', data);
    });

// ...

The iFrame script will look something like this:

/* iframe.js */

window.addEventListener('message', ({ data, ports }) => {
    if (data && ports && ports[0]) {
        if (data.type === 'INIT') {
            console.log('Received init request:', data.initData);
            ports[0].postMessage('Init success!');
            ports[0].close();
        }
    }
});

Tests

Simply clone the repo and run

npm install
npm test

License

MIT

About

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.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published