npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@knowledgecode/messenger

v0.5.0

Published

Req/Rep Pub/Sub library for iframes and workers

Downloads

7

Readme

Messenger

Messenger is a Req/Rep Pub/Sub library for iframes and workers.

Features

Allows messages to be exchanged between ...

  • the main window and one or more iframes / workers.
  • multiple iframes.
  • multiple components.

Installation

via npm:

npm i @knowledgecode/messenger

Usage

import { MessengerClient, MessengerServer } from '@knowledgecode/messenger';

ES Modules:

<script type="module">
  import { MessengerClient, MessengerServer } from '/path/to/esm/messenger.js';
</script>

Traditional:

<script src="/path/to/umd/messenger.js"></script>
<script>
  // It is provided with the global variable name "messenger".
  const { MessengerClient, MessengerServer } = self.messenger;
</script>

Simple Example

main.js

import { MessengerClient } from '/path/to/esm/messenger.js';

const messenger = new MessengerClient();
const worker = new Worker('/path/to/worker.js');

(async () => {
    await messenger.connect('example', worker);

    const answer = await messenger.req('add', { x: 2, y: 3 });

    console.log(answer);    // => 5

    messenger.send('close');
    messenger.disconnect();
})();

worker.js

importScripts('/path/to/umd/messenger.js');

const { MessengerServer } = self.messenger;
const messenger = new MessengerServer('example', self);

messenger.bind('add', data => {
    return data.x + data.y;
});

messenger.bind('close', () => {
    messenger.close();
    // Close this worker.
    self.close();
});

MessengerClient API

constructor()

const messenger = new MessengerClient();

connect(name, [endpoint[, options]])

  • {string} name - unique name of the MessengerServer to connect to
  • {Object} [endpoint] - an object that actually executes the postMessage()
  • {Object} [options] - connection options

The MessengerClient must connect to a MessengerServer via endpoint before communication can begin. To identify the MessengerServer to connect to, pass the unique name of the MessengerServer as the first argument. The endpoint is the object that actually executes the postMessage(). If omitted, it is assumed that self is set. The options are connection options and members of this object are targetOrigin and timeout (msec). If the timeout is omitted, this method will wait forever for a successful connection.

// To connect from the main window to a iframe.
const iframe = window.frames[0];

await messenger.connect('iframe', iframe, { targetOrigin: '*', timeout: 1000 })
    .catch(e => console.log(e));
// To connect from the main window to a worker.
const worker = new Worker('/path/to/worker.js');

await messenger.connect('worker', worker, { timeout: 1000 })
    .catch(e => console.log(e));

disconnect()

Disconnects from the server.

messenger.disconnect();

send(topic[, data])

  • {string} topic - topic name
  • {Object} [data] - an object to send

Sends a message (some object) to a topic. This method does not wait for any reply. A MessengerServer can receive the message if it is bound to the same topic name in advance.

messenger.send('greeting', { hello: 'world' });

req(topic[, data[, timeout]])

  • {string} topic - topic name
  • {Object} [data] - an object to send
  • {number} [timeout] - timeout (msec)

Sends a message (some object) to a topic. This method waits for some reply unlike send(). If timeout (msec) is omitted, this method waits forever for some reply.

const answer = await messenger.req('add', { x: 2, y: 3 })

console.log(answer);
await messenger.req('add', { x: 2, y: 3 }, 5000)
    .catch(e => console.log(e));    // Catch timeout error.

subscribe(topic, listener)

  • {string} topic - topic name
  • {Function} listener - a listener to receive published messages

Subscribes to messages on a topic.

messenger.subscribe('news', data => console.log(data));

unsubscribe(topic[, listener])

Unsubscribes to messages on a topic. If listener is omitted, all listeners for the topic are cleared.

  • {string} topic - topic name
  • {Function} [listener] - a listener to receive published messages
const listener = data => console.log(data);
messenger.subscribe('news', listener);

messenger.unsubscribe('news', listener);

MessengerServer API

constructor(name, [endpoint])

  • {string} name - unique name of the MessengerServer
  • {Object} [endpoint] - an object that actually executes the postMessage()
const messenger = new MessengerServer('server', self);

The name is a unique name by which clients identify this MessengerServer. The endpoint is the object that actually executes the postMessage(). If omitted, it is assumed that self is set.

bind(topic, listener)

  • {string} topic - topic name
  • {Function} listener - a listener to receive messages

Binds a listener to listen for messages on a topic. The topic names must be unique, no other listener than the first can bind on the same topic name. This method returns true or false as binding result.

messenger.bind('greeting', data => console.log(data));

messenger.bind('add', data => {
    // Reply to client.
    return data.x + data.y;
});

publish(topic, data)

  • {string} topic - topic name
  • {Object} data - an object to publish

Publish a message (some object) to all subscribers on a topic. This method does not wait for reply from the subscribers, and also does not fail even there are no subscribers at all.

messenger.publish('notification', 'The process completed successfully.');

close()

Closes all connections and shuts down the server.

messenger.close();

Browser support

Chrome, Safari, Firefox, Edge

License

MIT