{"id":16326689,"url":"https://github.com/chrisyip/shimo-broadcastchannel","last_synced_at":"2025-10-28T03:10:25.866Z","repository":{"id":173680723,"uuid":"486926009","full_name":"chrisyip/shimo-broadcastchannel","owner":"chrisyip","description":null,"archived":false,"fork":false,"pushed_at":"2023-01-18T08:56:33.000Z","size":649,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-17T06:41:30.836Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chrisyip.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-04-29T10:11:18.000Z","updated_at":"2023-06-08T14:10:02.000Z","dependencies_parsed_at":null,"dependency_job_id":"85734611-0f92-4611-b2af-db328ceb3480","html_url":"https://github.com/chrisyip/shimo-broadcastchannel","commit_stats":null,"previous_names":["chrisyip/shimo-broadcastchannel"],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrisyip%2Fshimo-broadcastchannel","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrisyip%2Fshimo-broadcastchannel/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrisyip%2Fshimo-broadcastchannel/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chrisyip%2Fshimo-broadcastchannel/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chrisyip","download_url":"https://codeload.github.com/chrisyip/shimo-broadcastchannel/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254235711,"owners_count":22036966,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-10T23:09:18.623Z","updated_at":"2025-10-28T03:10:20.809Z","avatar_url":"https://github.com/chrisyip.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ShimoBroadcastChannel\n\n基于 [BroadcastChannel]() 封装了一个更易用的通信库。\n\n兼容 Chrome、IE 11、Firefox 和 Safari，但需要 `Object.assign()`，在 IE 11 下使用需要引入 polyfill。\n\n# Usage\n\n```typescript\nimport { ShimoBroadcastChannel } from 'shimo-broadcast-channel'\n\nconst channel = new ShimoBroadcastChannel({\n  channelId: 'test'\n})\n\nawait channel.postMessage('message')\n\nchannel.on('message', (msg: ShimoMessageEvent) =\u003e {\n  handleMessageData(msg.data)\n})\n\n// 直接从其他频道取回值\nconst myValue = await channel.invoke('my_method', [arg1, arg2, ...])\n```\n\n## Context\n\nContext 是用于传递和消息有关的上下文，在消息传递时会保留。\n\n`Context.audiecen: string`\n\n用于限定消息听众，比如 `channel.postMessage(msg, { audience: 'a' })`，以便过滤消息处理器：\n\n- `on('message', fn, { audience: 'a' })` 会收到消息\n- `on('message', fn, { audience: 'b' })` 不会收到消息\n- `on('message', fn, { audience: '' })` 不会收到消息\n- `on('message', fn)` 不会收到消息\n\n`channel.invoke(method, [], { audience: 'a' })`：\n\n- `addInvokeHandler(method, fn, { audience: 'a' })` 会收到消息\n- `addInvokeHandler(method, fn, { audience: 'b' })` 不会收到消息\n- `addInvokeHandler(method, fn, { audience: '' })` 不会收到消息\n- `addInvokeHandler(method, fn)` 不会收到消息\n\n传入 `'*'` 则会忽略收到消息的 `audience`，不进行过滤。\n\n## BroadcastChannel 无法使用时\n\n在 BroadcastChannel 无法使用的场合，比如 cross origin，可以用 `channel.addMessagePoster()` 和 `channel.distributeMessage()` 转发消息。\n\n以 iframe 为例。\n\nParent window：\n\n```typescript\nimport {\n  SOURCE_NAMESPACE, // 'ShimoBroadcastChannel'\n  ShimoBroadcastChannel\n} from 'shimo-broadcast-channel'\n\nconst iframe = document.querySelector('iframe')\n\nconst channel = new ShimoBroadcastChannel({\n  channelId: 'test'\n})\n\n// 监听 postMessage 事件，把消息通过其他方式发出去\nchannel.on('postMessage', (evt: ShimoMessageEvent) =\u003e {\n  iframe.contentWindow.postMessage(evt, '*')\n})\n\nwindow.addEventListener('message', (evt: MessageEvent) =\u003e {\n  // 如果消息符合规则，则让 channel 来分发消息\n  if (evt.data \u0026\u0026 evt.data.source === SOURCE_NAMESPACE) {\n    channel.distributeMessage(evt.data)\n    // 将消息转发到 same origin channel\n    channel.postMessage(evt.data).catch(errorHandler)\n  }\n})\n\nchannel.addInvokeHandler('greeting', (name: string) =\u003e {\n  return `Hello, ${name}`\n})\n\nchannel.on('message', (evt: ShimoMessageEvent) =\u003e {\n  console.log(evt.data) // 'Hello, John'\n})\n```\n\niframe window：\n\n```typescript\nimport {\n  SOURCE_NAMESPACE,\n  ShimoBroadcastChannel\n} from 'shimo-broadcast-channel'\n\nconst channel = new ShimoBroadcastChannel({\n  channelId: 'test'\n})\n\n// 监听 postMessage 事件，把消息通过其他方式发出去\nchannel.on('postMessage', (evt: ShimoMessageEvent) =\u003e {\n  window.parent.postMessage(evt, '*')\n})\n\nwindow.addEventListener('message', (evt: MessageEvent) =\u003e {\n  // 如果消息符合规则，则让 channel 来分发消息\n  if (evt.data \u0026\u0026 evt.data.source === SOURCE_NAMESPACE) {\n    channel.distributeMessage(evt.data)\n    // 将消息转发到 same origin channel\n    channel.postMessage(evt.data).catch(errorHandler)\n  }\n})\n\nchannel.invoke('greeting', ['John']).then((msg: string) =\u003e {\n  console.log(msg) // 'Hello, John'\n\n  channel.postMessage(msg)\n})\n```\n\n\u003e 多重 iframe 嵌套或一个 window 嵌套多个 iframe，用上述方式会导致 BroadcastChannel 中有多条重复消息，建议只在单 window 到单 iframe 的情况下使用，或使用 `onMessageArrive` 进行去重。\n\n```typescript\nconst channel = new ShimoBroadcastChannel()\n\nconst cache = new SomeCache({ ttl: CACHE_TTL })\n\nchannel.onMessageArrive = async (evt: ShimoMessageEvent) =\u003e {\n  // 抛弃超过缓存时间后收到的旧消息\n  if (Date.now() - evt.time \u003e CACHE_TTL) {\n    return\n  }\n\n  // 消息在 cache 中说明被处理过\n  if (await cache.has(evt.id)) {\n    return\n  }\n  cache.add(evt.id)\n  return evt\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchrisyip%2Fshimo-broadcastchannel","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchrisyip%2Fshimo-broadcastchannel","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchrisyip%2Fshimo-broadcastchannel/lists"}