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

msgr

v2.0.0

Published

Nifty worker/client postMessage utility

Downloads

852

Readme

msgr

Nifty worker/client postMessage utility

Made with ❤ at @outlandish

js-standard-style

Makes communication between a client and service worker super easy...

  • Send messages from client -> worker and worker -> client with one call to channel.send()
  • Simple API: send anonymous data-only messages, typed-only messages, or typed messages with data
  • Register handlers for typed messages and anonymous messages
  • Easily respond to any message by calling respond() in the handler
  • Receive a response for a message using the familiar Promise then() method

Table of Contents

Import

// ES6
import msgr from 'msgr'

// CommonJS
var msgr = require('msgr')

// RequireJS
define(['msgr'], function (msgr) {/*...*/})
<!-- Script, available as `window.msgr` -->
<script src="/node_modules/msgr/index.js"></script>

Initialise & Example

Client: msgr.client()

Pass in reference to the worker and a collection of message handlers:

const recipient = navigator.serviceWorker.controller

const channel = msgr.client(recipient, {
  // Predefined message handlers
  SAY_HELLO: (data) => console.log('Hello, ' + data) //=> 'Hello, World!'
})

// Send something "unknown" to the worker.
// Notice it does not have a tag.
channel.send({
  username: 'Flanders',
  location: 'Springfield'
})

// Send a "known" message to the worker
channel.send('CACHE_ASSET', '/cat.gif').then(function (message) {
  console.log(message) //=> 'Caching complete!'
})

Worker: msgr.worker()

On the worker you just pass in your message handlers:

const channel = msgr.worker({
  CACHE_ASSET: cacheAsset
})

channel.receive(function (data) {
  // Do something with an "unknown" message
  // that does not have a predefined handler.
  console.log(data) //=> { username: 'Flanders', ... }
})

// Send something "known" to the client using a tag.
channel.send('SAY_HELLO', 'World!')

function cacheAsset (url, respond) {
  doCaching().then(function () {
    respond('Caching complete!')
  })
}

msgr API

msgr.client(serviceWorker, handlers) : Channel

Initialise a msgr client.

  • serviceWorker {ServiceWorkerRegistration} Worker that will receive messages sent via channel
  • handlers {Object} An object of message type/handler mappings

Returns a Channel. See the Channel API Docs for more details.

Example:

msgr.client(navigator.serviceWorker.controller, {
  NOTIFY: function (respond) {
    new Notification('You have a notification!')
    respond('GOT_THE_NOTIFICATION')
  }
})

msgr.worker(handlers) : Channel

Initialise a msgr worker.

  • handlers {Object} An object of message type/handler mappings

Returns a Channel. See the Channel API Docs for more details.

Example:

msgr.worker({
  NOTIFY: function (respond) {
    new Notification('You have a notification!')
    respond('GOT_THE_NOTIFICATION')
  }
})

Channel API

channel.ready(handler)

Register a handler to be called when the channel is opened between client and worker.

  • handler {Function} The ready handler

Although you can register ready handlers, you can send messages before the channel is open using channel.send() and these will be queued and sent as soon as the channel is ready.

Example:

channel.ready(function () {
  application.start()
})

channel.send([type,] data) : Promise

Send a message through the channel to the worker/client.

  • [type] {String} (optional) The message type
  • data {Any} The message data (it will be JSON.stringify'd)

Returns a Message. See the Message API Docs for more details.

If called before the channel is ready the message will be queued and sent as soon as the channel is open.

Example:

// Typed message, will invoke registered type handlers
channel.send('NOTIFY_USER')

// Typed message with data, will invoke registered type handlers
channel.send('NOTIFY_USER', { message: 'Update complete' })

// Anonymous, will invoke `receive` handlers
channel.send('This is the untagged data')

channel.receive(handler)

Handle an "unknown" message that is not tagged.

  • handler {Function} The message handler

The handler receives two arguments: the data of the message and a respond function.

Example:

channel.receive(function (data, respond) {
  console.log('Got some unknown data: ' + data)
})

Message API

message.then(handler)

Register a handler to receive the response to a message.

  • handler {Function} Response handler

Example:

// In client message handlers
msgr({
  NOTIFY_USER: function (data, respond) {
    new Notification('Job ' + data.id + ' was completed')
    respond('From worker: job deleted') // ACK
  }
})

// In worker
channel.send('NOTIFY_USER', { id: 1337 }).then((data) => {
  console.log(data) //=> 'From worker: job deleted'
})

respond([data])

Send a response to a received message.

This function is passed as the second argument to both "known" and "unknown" message handlers.

  • [data] {Any} (optional) The data to respond to the message with

Contributing

All pull requests and issues welcome!

If you're not sure how, check out Kent C. Dodds' great video tutorials on egghead.io!

Author & License

msgr was created by Sam Gluck and is released under the MIT license.