coframe
Cross-origin iframe messenger.
npm i coframe
Usage
coframe
is designed for TypeScript, though of course TS is optional. Basic
usage looks like this, just be sure your iframe
is fully loaded in the
browser. Note the separate files.
Parent
import { connect } from "coframe";
const parent = connect(document.getElementById("my-iframe"));
parent.emit("init");
Child
import { listen } from "coframe";
const child = listen();
child.on("init", (data) => {
});
Multiple Connections
By default, coframe
assumes a single connection. To enable multiple
connections to the same iframe, and/or to enhance security, pass a connection
name when creating a connection or listener.
This will ensure that events from other coframe instances do not interfere with
yours. Plus, after establishing a connection, coframe
will ignore events from any
source other than the source that established that connection.
import { connect, listen } from "coframe";
const parent = connect(iframe, "my-connection");
const child = listen("my-connection");
Typescript
coframe
really shines when used with TypeScript because it allows you to
strictly type the events and payloads sent between windows. To do so, you'll
need a shared type interface that can be included in the compiled bundles of
both the parent and child windows.
Here, each key of the type corresponds to an event name, and each value
corresponds to the payload of that event. For events with no payload, specify
undefined
.
type InitPayload = {
name: string;
date: string;
};
export type Events = {
init: InitPayload;
open: undefined;
close: undefined;
};
Usage then looks very similar, but you'll get strict type checking in dev.
import { connect } from "coframe";
import { Events } from "./shared/events";
const parent = connect<Events>(document.getElementById("my-iframe"));
parent.emit("init", {
name: "Truework",
date: new Date(),
});
parent.emit("open");
import { listen } from "coframe";
import { Events } from "./shared/events";
const child = listen<Events>();
child.on("init", ({ name, date }) => {});
child.on("open", () => {});
License
MIT License © Truework