UNPKG

@toruslabs/broadcast-channel

Version:

A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers

62 lines (58 loc) 1.58 kB
'use strict'; var util = require('../util.js'); const microSeconds = util.microSeconds; const type = "native"; function create(channelName) { const state = { time: util.microSeconds(), 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 util.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; } exports.averageResponseTime = averageResponseTime; exports.canBeUsed = canBeUsed; exports.close = close; exports.create = create; exports.microSeconds = microSeconds; exports.onMessage = onMessage; exports.postMessage = postMessage; exports.type = type;