https://github.com/pixelass/esdeka
Communicate between iframe and host
https://github.com/pixelass/esdeka
broadcast communication hooks iframe message postmessage reactjs
Last synced: 9 months ago
JSON representation
Communicate between iframe and host
- Host: GitHub
- URL: https://github.com/pixelass/esdeka
- Owner: pixelass
- License: mit
- Created: 2022-11-23T19:37:52.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-04-01T15:44:31.000Z (about 3 years ago)
- Last Synced: 2025-09-29T15:52:04.145Z (9 months ago)
- Topics: broadcast, communication, hooks, iframe, message, postmessage, reactjs
- Language: TypeScript
- Homepage:
- Size: 1.18 MB
- Stars: 12
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: .github/CONTRIBUTING.md
- License: LICENSE
- Code of conduct: .github/CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Esdeka
Communicate between `` and host
[](https://app.codacy.com/gh/pixelass/esdeka/dashboard?branch=main)
[](https://app.codacy.com/gh/pixelass/esdeka/dashboard?branch=main)
[](https://snyk.io/test/github/pixelass/esdeka)
[](https://www.npmjs.com/package/esdeka)
[](https://www.npmjs.com/package/esdeka)
[](https://github.com/pixelass/esdeka/blob/main/LICENSE)

[](https://github.com/sponsors/pixelass)
## Table of Contents
- [Mechanism](#mechanism)
- [Creating a connection](#creating-a-connection)
- [Functions](#functions)
- [`call`](#call)
- [`answer`](#answer)
- [`disconnect`](#disconnect)
- [`subscribe`](#subscribe)
- [`dispatch`](#dispatch)
- [`broadcast`](#broadcast)
- [React hooks](#react-hooks)
- [`useHost`](#usehost)
- [`useGuest`](#useguest)
- [Bundle size](#bundle-size)
- [Full React example (using Zustand)](#full-react-example-using-zustand)
## Mechanism
Esdeka is a small and lightweight library that provides a simple mechanism for communication between a host window and one or more guest iframes. It uses [`window.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) to transmit data between the two, and offers several helper functions to make the process as easy as possible.
With Esdeka, you can stream data down to the iframe, and if the iframe needs to communicate back, it can dispatch an action with an optional payload. You can then choose how to respond to the transmitted data.
Esdeka is easy to use and offers a range of functions to create and manage connections, including `call`, `answer`, `broadcast`, and `subscribe`. It also includes a set of React hooks for even simpler integration with your React projects.
With all bundles smaller than 1KB, Esdeka is a great choice for lightweight communication between your web pages and iframes.
Flux flow
### Creating a connection
To create a connection we need to call a client and wait for an answer.
Setting up a **Host**.
```ts
import { call } from "esdeka";
const iframe = document.querySelector("iframe");
call(iframe.contentWindow, "my-channel", { some: "Data" });
```
Setting up a **Guest**.
```ts
import { answer, subscribe } from "esdeka";
subscribe("my-channel", event => {
if (event.data.action.type === "call") {
answer(event.source, "my-channel");
}
});
```
Once a connection exists, we can broadcast information from the host to the guest.
**Host**
```ts
import { broadcast, call, subscribe } from "esdeka";
const iframe = document.querySelector("iframe");
call(iframe.contentWindow, "my-channel", { some: "Data" });
subscribe("my-channel", event => {
if (event.data.action.type === "answer") {
broadcast(event.source, "my-channel", {
question: "How are you?",
});
}
});
```
The guest subscribes to all messages and act accordingly.
**Guest**
```ts
import { answer, subscribe } from "esdeka";
const questions = [];
subscribe("my-channel", event => {
const { type, payload } = event.data.action;
switch (type) {
case "broadcast":
if (payload?.question) {
questions.push(payload.question);
}
break;
case "call":
answer(event.source, "my-channel");
break;
default:
console.error("Not implemented");
break;
}
});
```
## Functions
### `call`
Sends a connection request from the host to a guest. The payload can be anything that you want to
send through a channel.
| Argument | Type | Description |
| --------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `Window` | Has to be a [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) to use [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) |
| `channel` | `string` | The channel on which the host and gues communicate. The host and guest have to use the same channel to communicate. |
| `payload` | `unknown` | The payload that of the message can contain any data. We cannot transmit functions or circular objects, therefore we recommend using a serializer. |
| `targetOrigin?` | `string` | Optional origin to prevent insecure communication. |
```ts
call(window, "my-channel", {
message: "Hello",
});
```
### `answer`
Answer to a host to confirm the connection.
| Argument | Type | Description |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `Window` | Has to be a [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) to use [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) |
| `channel` | `string` | The channel on which the host and gues communicate. The host and guest have to use the same channel to communicate. |
| `targetOrigin?` | `string` | Optional origin to prevent insecure communication. |
```ts
answer(window, "my-channel");
```
### `disconnect`
Tell the host that the guest disconnected.
| Argument | Type | Description |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `Window` | Has to be a [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) to use [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) |
| `channel` | `string` | The channel on which the host and gues communicate. The host and guest have to use the same channel to communicate. |
| `targetOrigin?` | `string` | Optional origin to prevent insecure communication. |
```ts
disconnect(window, "my-channel");
```
### `subscribe`
Listen to all messages in a channel.
| Argument | Type | Description |
| --------------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `Window` | Has to be a [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) to use [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) |
| `channel` | `string` | The channel on which the host and gues communicate. The host and guest have to use the same channel to communicate. |
| `callback` | `(event: MessageEvent) => void` | The callback function of the subscription |
| `targetOrigin?` | `string` | Optional origin to prevent insecure communication. |
```ts
subscribe("my-channel", event => {
console.log(event);
});
```
### `dispatch`
Send an action to Esdeka. The host will be informed and can act un the request.
| Argument | Type | Description |
| --------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `Window` | Has to be a [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) to use [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) |
| `channel` | `string` | The channel on which the host and gues communicate. The host and guest have to use the same channel to communicate. |
| `action` | `Action` | The action that is dispatched by the guest. |
| `targetOrigin?` | `string` | Optional origin to prevent insecure communication. |
**Without payload**
```ts
dispatch(window, "my-channel", {
type: "increment",
});
```
**With payload**
```ts
dispatch(window, "my-channel", {
type: "greet",
payload: {
message: "Hello",
},
});
```
### `broadcast`
Send data from the host window to the guest. The payload can be anything that you want to send
through a channel.
| Argument | Type | Description |
| --------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | `Window` | Has to be a [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) to use [`postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) |
| `channel` | `string` | The channel on which the host and gues communicate. The host and guest have to use the same channel to communicate. |
| `payload` | `unknown` | The payload that of the message can contain any data. We cannot transmit functions or circular objects, therefore we recommend using a serializer. |
| `targetOrigin?` | `string` | Optional origin to prevent insecure communication. |
```ts
broadcast(window, "my-channel", {
message: "Hello",
});
```
## React hooks
### `useHost`
Curried host functions that don't need the window and channel.
```tsx
const { broadcast, call, subscribe } = useHost(ref, "my-channel");
call({
message: "Hello",
});
broadcast({
message: "Hello",
});
subscribe(event => {
console.log(event);
});
```
### `useGuest`
Curried guest functions that don't need the window and channel.
```tsx
const { answer, disconnect, dispatch, subscribe } = useGuest(ref, "my-channel");
answer();
disconnect();
subscribe(event => {
console.log(event);
});
dispatch({
type: "greet",
payload: {
message: "Hello",
},
});
```
## Bundle size
All bundles are smaller than 1KB
```shell
PASS ./dist/index.js: 568B < maxSize 1KB (gzip)
PASS ./dist/index.mjs: 526B < maxSize 1KB (gzip)
PASS ./dist/react.js: 752B < maxSize 1KB (gzip)
PASS ./dist/react.mjs: 729B < maxSize 1KB (gzip)
```
## Full React example (using Zustand)
**Host**
`http://localhost:3000/`
```tsx
import { serialize, useHost } from "esdeka/react";
import { DetailedHTMLProps, IframeHTMLAttributes, useEffect, useRef, useState } from "react";
import create from "zustand";
export interface StoreModel {
counter: number;
increment(): void;
decrement(): void;
}
export const useStore = create(set => ({
counter: 0,
increment() {
set(state => ({ counter: state.counter + 1 }));
},
decrement() {
set(state => ({ counter: state.counter - 1 }));
},
}));
export interface EsdekaHostProps
extends DetailedHTMLProps, HTMLIFrameElement> {
channel: string;
maxTries?: number;
interval?: number;
}
export function EsdekaHost({ channel, maxTries = 30, interval = 30, ...props }: EsdekaHostProps) {
const ref = useRef(null);
const connection = useRef(false);
const [tries, setTries] = useState(maxTries);
const { broadcast, call, subscribe } = useHost(ref, channel);
// Send a connection request
useEffect(() => {
if (connection.current || tries <= 0) {
return () => {
/* Consistency */
};
}
call(serialize(useStore.getState()));
const timeout = setTimeout(() => {
call(serialize(useStore.getState()));
setTries(tries - 1);
}, interval);
return () => {
clearTimeout(timeout);
};
}, [call, tries, interval]);
useEffect(() => {
if (!connection.current) {
const unsubscribe = subscribe(event => {
const store = useStore.getState();
const { action } = event.data;
switch (action.type) {
case "answer":
connection.current = true;
break;
default:
if (typeof store[action.type] === "function") {
store[action.type](action.payload.store);
}
break;
}
});
return () => {
unsubscribe();
};
}
return () => {
/* Consistency */
};
}, [subscribe]);
// Broadcast store to guest
useEffect(() => {
if (connection.current) {
const unsubscribe = useStore.subscribe(newState => {
broadcast(serialize(newState));
});
return () => {
unsubscribe();
};
}
return () => {
/* Consistency */
};
}, [broadcast]);
return ;
}
export default function App() {
const increment = useStore(state => state.increment);
const decrement = useStore(state => state.decrement);
const counter = useStore(state => state.counter);
return (
Up
{counter}
Down
);
}
```
**Guest**
`http://localhost:3001`
```tsx
import { useGuest } from "esdeka/react";
import { useEffect, useRef } from "react";
import create from "zustand";
export interface StoreModel {
[key: string]: any;
// eslint-disable-next-line no-unused-vars
set(state: Omit): void;
}
export const useStore = create(set => ({
set(state) {
set(state);
},
}));
export function EsdekaGuest({ channel }: { channel: string }) {
const counter = useStore(state => state.counter);
const host = useRef(null);
const { answer, dispatch, subscribe } = useGuest();
useEffect(() => {
const unsubscribe = subscribe>(event => {
const { action } = event.data;
switch (action.type) {
case "call":
host.current = event.source as Window;
answer();
break;
case "broadcast":
useStore.getState().set(action.payload);
break;
default:
break;
}
});
return () => {
unsubscribe();
};
}, [answer, subscribe]);
return (
Current Count: {counter}
{
dispatch({ type: "decrement" });
}}
>
Down
{
dispatch({ type: "increment" });
}}
>
Up
);
}
export default function Page() {
return ;
}
```