https://github.com/flymeth/better-postmessage
window.postMessage, but supports Promises, answers and simple typed handling
https://github.com/flymeth/better-postmessage
Last synced: 9 months ago
JSON representation
window.postMessage, but supports Promises, answers and simple typed handling
- Host: GitHub
- URL: https://github.com/flymeth/better-postmessage
- Owner: Flymeth
- Created: 2024-06-10T13:52:29.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-06-12T13:22:12.000Z (about 2 years ago)
- Last Synced: 2025-08-09T02:28:29.952Z (11 months ago)
- Language: JavaScript
- Size: 26.4 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# Better postMessage
Tired of the `window.postMessage()` method ? Need fresh new API that support Promises, answers and simple typed handling ?
BetterPostMessage will resolve all of that !
## Installation
```terminal
# NPM
npm i --save better-postmessage
# YARN
yarn i --save better-postmessage
# BUN
bun i --save better-postmessage
```
## Usage
### First context
```ts
import BetterPostMessage from "better-postmessage";
const messenger = new BetterPostMessage(window);
messenger
.post({ message: "ping" })
.answer.then((answer) => {
if (answer === "pong") console.log("Second context is online !");
})
.catch(() => {
console.log("Second context has not responded");
});
```
### Second context
```ts
import BetterPostMessage from "better-postmessage";
const messenger = new BetterPostMessage(window);
messenger.onReceive(({ message }) => {
if (message === "ping") return "pong";
});
```
### Parameters
#### Constructor arguments
```js
new BetterPostMessage(context, options?)
```
##### Context
The Window-based context where to emit/receive messages
##### Options?
> Not required
The object containing all behavior options of the messenger.
Here are the different options :
| KEY | DESCRIPTION | TYPE | DEFAULT VALUE |
| ------------- | ---------------------------------------------------------------------------------------------------- | --------- | ------------- |
| tunnel | Specify the custom tunnel of the proxy. Handler and message will be only receive/send to this tunnel | `string` | `""` |
| answerTimeout | In milliseconds, the maximum amount of time a message can wait for its answer | `number` | `15_000` |
| debug | If you want to view what's appening behind the process | `boolean` | `false` |