message-port-api
a repository npm package
https://tachibana-shin.github.io/message-port-api
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
```ts
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>, // processing functions
targetOptions?: string | WindowPostMessageOptions // option 2 propagates to `postMessage`
): 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]>>