xwm
v0.0.3
Published
Simple cross-window messaging library
Downloads
2
Maintainers
Readme
XWM
Cross-window messaging library.
Usage
npm install xwm
Main Window
import { create } from "/lib/main.ts";
// Define the events
interface EventMap {
ping: { timestamp: number };
pong: { timestamp: number };
}
const url = "http://example.com";
// Create instance
const xwm = create<EventMap>(url);
// Open window in an iframe and pass the token
const iframe = document.createElement("iframe");
iframe.src = `${url}?token=${xwm.createToken()}`;
document.body.appendChild(iframe);
// Register the created window
xwm.setPeerWindow(iframe.contentWindow);
// Listen for events
xwm.on("pong", (payload) => {
console.log("Pong received", payload.timestamp);
});
// Emit events
xwm.emit("ping", { timestamp: Date.now() });
Peer Window
import { createFromToken } from "/lib/main.ts";
// Get the token
const params = new URLSearchParams(location.search).get("token");
// Create instance from token
const xwm = createFromToken<EventMap>(token);
// Listen for events
xwm.on("ping", (payload) => {
console.log("Ping received", payload.timestamp);
// Emit events
xwm.emit("pong", { timestamp: Date.now() });
});