message-port-api
A simple package that allows you to simplify the use of MessagePort API more easily (Worker, IFrame...)
This is a very simple package. it cannot transfer complex data such as function
or class
. if you want to use API
containing complex data use workercom

Installation
NPM / Yarn / Pnpm
pnpm add message-port-api
Usage
Worker
worker.ts
import { useReceive } from "message-port-api"
const receive = useReceive(self)
const controllers = receive({
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"
import { useSend } from "message-port-api"
const worker = new Worker()
const send = useSend(worker)
console.log(await send<Controller>("sum", [1, 2]))
IFrame
iframe
import { useReceive } from "message-port-api"
const receive = useReceive(window, parent)
receive(
{
changeBg(color: string) {
document.body.style.backgroundColor = color
}
},
{
targetOrigin: "*"
}
)
main.ts
import { useSend } from "message-port-api"
const send = useSend(window, () => iframe.contentWindow)
await send("changeBg", ["red"])
API
useReceive
This function will be located on the host
side to handle the requested tasks
function useReceive(
sender: Sender,
receiver: Receiver
): receive
function receive(
controllers: Record<string, Function>,
targetOptions?: string | WindowPostMessageOptions
): Controller
If you want to cancel the call receive.cancel()'. This is useful when you use
receive` in components
import { useReceive } from "message-port-api"
const receive = useReceive(self)
receive({ sum })
receive.cancel()
useSend
This function will be on the client
side to send processing requests and return a Promise containing processed results from receive
function
function useSend(
sender: Sender,
receiver: Receiver
timeout: boolean | number = 30000
): send
function send<Controllers>(
name: keyof Controllers,
arguments: Arguments<Controllers[name]>,
targetOptions?: string | WindowPostMessageOptions
): Promise<ReturnType<Controllers[name]>>