post-any-message

Like browser postMessage(), but you can transfer functions and stuff

Usage no npm install needed!

<script type="module">
  import postAnyMessage from 'https://cdn.skypack.dev/post-any-message';
</script>

README

post-any-message

Created with JavaScript Style Guide

Like browser postMessage(), but you can transfer functions and stuff

Use Case

There are many environments when you have to use postMessage() to communicate (like Web Workers, Service Workers, Chrome Extensions).

Posting messages let's you transfer data like numbers, strings, objects, and arrays. But what if you wanted to transfer a function? The goal of this package is to let you transfer anything.

Examples

You can find examples in the test directory in the git repo.

What can be transferred?

This is the list of things that can be transferred. If you want to transfer something that's not on the list, make an issue and it will probably be added to the list. One thing that could be added is transferring promises.

  • array
  • boolean
  • function (can transfer any parameters and return values that are on this list)
  • number
  • object
  • string

Note about transferring functions

A MessageChannel is used to tell one context to call the function. Since message responses are not called synchronously, all functions are turned into async functions. For example, if you are transferring the following code:

(a, b) => a + b

You would have to call it like this:

const decodedFnIsNowAsync = decode(transferredFunction)
await decodedFnIsNowAsync(5, 6)