beaverjs
Version:
An abstraction around WebExtension messaging
40 lines • 1.54 kB
JavaScript
import { BaseEventHandler } from './BaseEventHandler';
import { Destination, isBackground, isContent, isContext, isWorker } from './destination';
import { listen } from './listeners';
export class ContentEventHandler extends BaseEventHandler {
constructor(listenFrom = ['context', 'background']) {
super();
this.listenFrom = listenFrom;
}
emitBackground(key, data) {
return this.emit(key, data, Destination.Background);
}
emitContext(key, data) {
return this.emit(key, data, Destination.Context);
}
sendEvent(serialized, destination) {
destination !== null && destination !== void 0 ? destination : (destination = Destination.Passthrough);
if (isContext(destination) || (isContent(destination) && isWorker(destination))) {
postMessage({ destination, data: serialized }, '*');
}
if (isBackground(destination) && globalThis.browser) {
browser.runtime.sendMessage({ destination, data: serialized });
}
}
serialize(type, data) {
return { data, event: type };
}
deserialize(serialized) {
return { data: serialized.data, type: serialized.event };
}
setup() {
listen({
thisActor: 'content',
listenFrom: new Set(this.listenFrom),
onMessage: (msg, sender) => {
this.handleSerialized(msg.data, sender);
},
});
}
}
//# sourceMappingURL=ContentEventHandler.js.map