@toruslabs/broadcast-channel
Version:
A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers
53 lines (50 loc) • 1.46 kB
JavaScript
import { microSeconds as microSeconds$1, PROMISE_RESOLVED_VOID } from '../util.js';
const microSeconds = microSeconds$1;
const type = "native";
function create(channelName) {
const state = {
time: microSeconds$1(),
messagesCallback: null,
bc: new BroadcastChannel(channelName),
subFns: [] // subscriberFunctions
};
state.bc.onmessage = msg => {
if (state.messagesCallback) {
state.messagesCallback(msg.data);
}
};
return state;
}
function close(channelState) {
channelState.bc.close();
channelState.subFns = [];
}
function postMessage(channelState, messageJson) {
try {
channelState.bc.postMessage(messageJson);
return PROMISE_RESOLVED_VOID;
} catch (err) {
return Promise.reject(err);
}
}
function onMessage(channelState, fn) {
channelState.messagesCallback = fn;
}
function canBeUsed() {
/**
* in the electron-renderer, isNode will be true even if we are in browser-context
* so we also check if window is undefined
*/
if (typeof window === "undefined") return false;
if (typeof BroadcastChannel === "function") {
if (BroadcastChannel._pubkey) {
throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");
}
return true;
}
return false;
}
function averageResponseTime() {
return 150;
}
export { averageResponseTime, canBeUsed, close, create, microSeconds, onMessage, postMessage, type };