message-port-api
A simple package that allows you to simplify the use of MessagePort API more easily (Worker, IFrame...)
Installation
NPM / Yarn / Pnpm
pnpm add message-port-api
Usage
Worker
worker.ts
import { receive } from "message-port-api"
const controllers = receive(
{
receiver: self,
sender: self
},
{
sum(a: number, b: number) {
return a + b
}
}
)
export type Controller = typeof controller
index.ts
import Worker from "./worker?worker"
import type { Controller } from "./worker"
const worker = new Worker()
console.log(
await sender<Controller>(
{
receiver: worker,
sender: worker
},
"sum",
[1, 2]
)
)
IFrame
iframe
import { receive } from "message-port-api"
receive(
{
receiver: parent,
sender: window
},
{
changeBg(color: string) {
document.body.style.backgroundColor = color
}
},
{
targetOrigin: "*"
}
)
main.ts
import { send } from "message-port-api"
await send(
{
get receiver() {
return iframe.contentWindow
},
sender: window
},
"changeBg",
["red"]
)
API
receive
This function will be located on the host
side to handle the requested tasks
function receive(
config: {
receiver: Receiver // contains `postMessage` function to send return results
sender: Sender // contains 2 functions `addEventListener` and `removeEventListener` to listen to and cancel the `message` event
},
controllers: Record<string, Function>,
targetOptions?: string | WindowPostMessageOptions
): Controller
sender
This function will be on the client
side to send processing requests and return a Promise containing processed results from receive
function
function sender<Controllers>(
config: {
receiver: Receiver
sender: Sender
},
name: keyof Controllers,
arguments: Arguments<Controllers[name]>,
targetOptions?: string | WindowPostMessageOptions
): Promise<ReturnType<Controllers[name]>>