A lightweight event library for cross context messaging and events synchronization
Cross context events is a robust, lightweight package providing the option to send and receive events across JS execution context.
You asked, what does this mean, exactly? Well, it means that when you emit an event in your script, the same event will also be emitted in all other linked execution contexts (i.e. other tabs, windows, processes), even on different computers if you want to! All you need to do is writing a few lines of code to link them together.
Try the demo here Source code for the demo
See here.
Comprehensive documentations
event.context.new
, then listeners forevent.context
and event
are also notified (but event.context2
isEven if you have a network of nested iframes like the image below, and you emit an event in iframe 9 (or any frame or the parent window for that matter), it will be emitted in all frames and the parent window. This also applies to a chain or child processes or workers or any other combinations of communication channels. See event relaying.
Unpkg
<script src="https://unpkg.com/cross-context-events/dist/cross-context-events.min.js"></script>
jsDelivr
<script src="https://cdn.jsdelivr.net/npm/cross-context-events/dist/cross-context-events.min.js"></script>
yarn
yarn add cross-context-events
npm
npm install cross-context-events
This example uses the WebWorker API , but it can be easily switched to Node processes, iFrames, or others by simply changing the transport used. For details, please refer to transports.
// index.js
import {
useGlobalTransport,
createDefaultTransport,
createEvent
} from "cross-context-events";
const OnlineEvent = createEvent("worker.online")
OnlineEvent.addListener(() => console.log("Worker is now online \(^▽^)/"))
let worker = new Worker("worker.js")
useGlobalTransport(createDefaultTransport({
type: "worker",
target: worker
}))
// worker.js
import {
useGlobalTransport,
createDefaultTransport,
createEvent
} from "cross-context-events";
useGlobalTransport(createDefaultTransport({
type: "worker",
target: self
}))
const OnlineEvent = createEvent("worker.online")
new OnlineEvent().emit()
As you can see, Worker is now online \(^▽^)/
has been logged to the console
from the main thread. Yay!
Please refer to the documentation for more information.