1.2.0 • Published 2 years ago

coframe v1.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

coframe

npm npm.io

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

// https://parent.com/index.js
import { connect } from "coframe";

const parent = connect(document.getElementById("my-iframe"));

parent.emit("init");

Child

// https://child.com/index.js
import { listen } from "coframe";

const child = listen();

child.on("init", (data) => {
  // do something
});

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.

// https://parent.com/index.js
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(), // TypeError
});
parent.emit("open");
// https://child.com/index.js
import { listen } from "coframe";
import { Events } from "./shared/events";

const child = listen<Events>();

child.on("init", ({ name, date }) => {}); // strictly typed parameters!
child.on("open", () => {});

License

MIT License © Truework

1.2.0

2 years ago

1.1.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.0.0

2 years ago