31 lines
1.5 KiB
JavaScript
31 lines
1.5 KiB
JavaScript
;(function (global) {
|
|
'use strict'
|
|
|
|
function createChannel(name, options) {
|
|
const opt = options || {}
|
|
const Factory = Object.prototype.hasOwnProperty.call(opt, 'BroadcastChannel') ? opt.BroadcastChannel : global.BroadcastChannel
|
|
let channel = null
|
|
let closed = false
|
|
let messages = 0
|
|
let errors = 0
|
|
const handlers = new Set()
|
|
const onMessage = (event) => { messages++; handlers.forEach((handler) => { try { handler(event && event.data, event) } catch (e) { errors++ } }) }
|
|
const onError = () => { errors++ }
|
|
if (typeof Factory === 'function' && name) {
|
|
try {
|
|
channel = new Factory(String(name))
|
|
channel.onmessage = onMessage
|
|
channel.onerror = onError
|
|
} catch (e) { errors++ ; channel = null }
|
|
}
|
|
return {
|
|
supported: !!channel,
|
|
post(value) { if (!channel || closed) return false; try { channel.postMessage(value); return true } catch (e) { errors++; return false } },
|
|
add(handler) { if (typeof handler !== 'function') return function () {}; handlers.add(handler); return () => handlers.delete(handler) },
|
|
close() { if (closed) return; closed = true; handlers.clear(); if (channel) { channel.onmessage = null; channel.onerror = null; try { channel.close() } catch (e) { errors++ } } },
|
|
snapshot() { return { name: String(name || ''), supported: !!channel, closed, handlers: handlers.size, messages, errors } },
|
|
}
|
|
}
|
|
global.IWBRuntimeChannel = { create: createChannel }
|
|
})(typeof window !== 'undefined' ? window : globalThis)
|