postmessage-duplexpostmessage-duplex
首页
指南
API
示例
🎮 Playground
  • FAQ
  • 更新日志
  • GitHub
  • 简体中文
  • English
GitHub
首页
指南
API
示例
🎮 Playground
  • FAQ
  • 更新日志
  • GitHub
  • 简体中文
  • English
GitHub
  • API 参考

    • API 参考
    • IframeChannel
    • ServiceWorkerChannel
    • 类型定义
    • 错误处理

API 参考

本节提供 postmessage-duplex 的完整 API 文档。

核心类

类描述
IframeChannel用于 iframe 双工通讯
ServiceWorkerChannel用于 Service Worker 双工通讯
ChannelError自定义错误类

类型定义

类型描述
Communicator通讯器接口
PostResponse响应数据结构
PostRequest请求数据结构
ChannelOption配置选项
PublishOptions发布选项

枚举

枚举描述
ReturnCode返回码枚举
ErrorCode错误码枚举

快速参考

IframeChannel

import { IframeChannel } from 'postmessage-duplex'

// 父页面
const channel = new IframeChannel(iframe, options?)

// 子页面
const channel = new IframeChannel(parentOrigin, options?)

// 方法
await channel.publish(cmdname, data?, options?)  // 发送并等待响应
await channel.call(methodName, params)           // 类型安全的远程调用
channel.subscribe(cmdname, callback)             // 订阅消息
channel.once(cmdname, callback)                  // 一次性订阅
channel.unSubscribe(cmdname)                     // 取消订阅
channel.destroy()                                // 销毁通道

// 属性
channel.isReady      // boolean - 是否就绪
channel.isSon        // boolean - 是否为子页面
channel.isDestroyed  // boolean - 是否已销毁

ServiceWorkerChannel

import { ServiceWorkerChannel } from 'postmessage-duplex'

// 页面端
const channel = await ServiceWorkerChannel.createFromPage(options?)

// Worker 端
const channel = ServiceWorkerChannel.createFromEvent(event, options?)
const channel = ServiceWorkerChannel.createFromWorker(clientId, options?)

// 方法与 IframeChannel 相同

配置选项

interface ChannelOption {
  timeout?: number                // 默认 5000ms
  log?: Console                   // 自定义日志
  subscribeMap?: Record<string, Function>  // 预定义订阅
  maxMessageSize?: number         // 最大消息大小
  rateLimit?: number              // 速率限制
}

发布选项

interface PublishOptions {
  timeout?: number               // 覆盖默认超时
  transferables?: Transferable[] // 可传输对象
}

返回码

enum ReturnCode {
  Success = 0,                    // 成功
  ReceiverCallbackError = -1,     // 接收方回调错误
  SendCallbackError = -2,         // 发送方回调错误
  NoSubscribe = -3,               // 未订阅
  TimeOut = -99                   // 超时
}

导入

// 命名导入
import { 
  IframeChannel,
  ServiceWorkerChannel,
  ChannelError,
  ReturnCode,
  ErrorCode,
  createConnectionDestroyedError,
  createTimeoutError,
  createHandlerError
} from 'postmessage-duplex'

// 类型导入
import type {
  PostResponse,
  PostRequest,
  PostCallback,
  ChannelOption,
  PublishOptions,
  Communicator,
  Methods,
  MethodParams,
  MethodReturn,
  TypedPostResponse
} from 'postmessage-duplex'
在 GitHub 上编辑此页
上次更新: 2026/1/26 09:07
贡献者: liquidliang
Next
IframeChannel