UNPKG

beaverjs

Version:

An abstraction around WebExtension messaging

38 lines 1.42 kB
import { BaseEventHandler } from './BaseEventHandler'; import { Destination } from './destination'; import { listen } from './listeners'; export class BackgroundEventHandler extends BaseEventHandler { constructor(query = {}) { super(); this.query = query; } emitContent(key, data) { return this.emit(key, data, Destination.Content); } emitContext(key, data) { return this.emit(key, data, Destination.Context); } sendEvent(serialized, destination) { destination !== null && destination !== void 0 ? destination : (destination = Destination.Passthrough); sendToAllTabs(this.query, { destination, data: serialized }); } serialize(type, data) { return { data, event: type }; } deserialize(serialized) { return { data: serialized.data, type: serialized.event }; } setup() { listen({ thisActor: 'background', listenFrom: new Set(['content']), onMessage: (msg, sender) => { this.handleSerialized(msg.data, sender); }, }); } } function sendToAllTabs(query, msg) { return browser.tabs.query(query).then(tabs => tabs.forEach(tab => { var _a; return browser.tabs.sendMessage((_a = tab.id) !== null && _a !== void 0 ? _a : -1, msg); })); } //# sourceMappingURL=BackgroundEventHandler.js.map