# @aspectly/transports 中文文档

规范地址：https://npmcn.com/package/%40aspectly/transports/

版本：2\.2\.0
npm 元数据更新时间：2026-09-05T22:31:34.560Z
中文译文更新时间：2026-11-06T23:51:15.551Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40aspectly/transports
原文对照：https://npmcn.com/package/%40aspectly/transports/?lang=original
项目主页：https://github.com/JeanIsahakyan/aspectly#readme
源码仓库：https://github.com/JeanIsahakyan/aspectly

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：323 kB，82 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2026-03-08T03:07:52.295Z
- 最新版本发布：2026-09-05T22:31:34.167Z
- 近 30 天下载量：5799（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：12（近 12 个月 12 个）

## 中文简介

视桥的运输层 - 站台检测和消息传递

## 安装

```sh
npm install @aspectly/transports
```

也可以使用：`pnpm add @aspectly/transports`、`yarn add @aspectly/transports`、`bun add @aspectly/transports`

## README

# @ spective/ 运算

[![npm version](https://img.shields.io/npm/v/@aspectly/transports?style=flat-square&logo=npm&color=cb3837)](https://www.npmjs.com/package/@aspectly/transports) [![npm downloads](https://img.shields.io/npm/dm/@aspectly/transports?style=flat-square&color=22c55e)](https://www.npmjs.com/package/@aspectly/transports)

传输层,用于在Web Publications,iframes,和Web应用程序之间进行跨平台通信.

## 安装

```bash
# npm
npm install @aspectly/transports

# pnpm
pnpm add @aspectly/transports

# yarn
yarn add @aspectly/transports
```

## 概览

`@aspectly/transports` 提供了灵活的抽象层,用于平台检测和消息通过不同执行背景. 它会自动检测当前环境(CefSharp,WKWebView/WebKitGTK,React Introduct WebView,Android WebView,Flutter WebView,iframe,或浏览器窗口),并为双向通信提供统一的API.

### 内建运输

| 运输 | 检测 | 优先权 | 使用大小写 |
| --- | --- | --- | --- |
| **CefSharp 运输** | `window.CefSharp.PostMessage` | 100个 | 带有 CefSharp (.NET 的铬嵌入框架) 的桌面应用程序 |
| **WebKit 运输** | `window.webkit.messageHandlers.aspectly` | 95 (韩语) | iOS/macOS/visionOS WKWebView 和 Linux WebKitGTK 互联网档案馆的存檔,存档日期2013-10-02 |
| **反向运输** | `window.ReactNativeWebView.postMessage` | 90 (韩语) | 反应原生网络视频 |
| **Android 运输公司** | `window.AspectlyAndroid.postMessage` | 85个 | Android 网络视频 |
| **小蝶运输** | `window.AspectlyFlutter.postMessage` | 84 (中文(简体) ) | 小蝶头 `webview_flutter` |
| **框架运输** | `window.parent !== window` | 80个 | Iframes内网络内容 |
| **窗口传输** | `window.opener !== null` | 70个 | 弹出窗口通过 `window.open` |
| **邮政运输** | 总是可用的( 基因) | 10个 | 常规 `window.postMessage` 倒计时 |
| **零运输** | 总是可用 | 倒计时 | 安全部门改革/测试的后退(无) |

### 自动检测

这个 `TransportRegistry` 根据优先级顺序自动选择适当的运输。 优先运输首先检查,确保使用最具体的运输:

```
cefsharp (100) > webkit (95) > react-native (90) > android (85) >
flutter (84) > iframe (80) > window (70) > postmessage (10) > null (fallback)
```

## 快速启动

### 自动检测( 建议)

```typescript
import { detectTransport } from '@aspectly/transports';

// Automatically detect the current environment
const transport = detectTransport();
// transport.name is one of: 'cefsharp', 'webkit', 'react-native', 'android',
// 'flutter', 'iframe', 'window', 'postmessage', or 'null'
console.log(`Using transport: ${transport.name}`);

// Send a message
transport.send(JSON.stringify({ type: 'hello', data: 'world' }));

// Subscribe to incoming messages
const unsubscribe = transport.subscribe((message) => {
  const data = JSON.parse(message);
  console.log('Received:', data);
});

// Cleanup when done
unsubscribe();
```

### 直接运输使用

```typescript
import { CefSharpTransport } from '@aspectly/transports';

const transport = new CefSharpTransport();

if (transport.isAvailable()) {
  transport.send(JSON.stringify({ method: 'getData' }));
}
```

### 自定义运输登记

```typescript
import { registerTransport, detectTransport } from '@aspectly/transports';

// Register a custom transport with high priority
registerTransport({
  name: 'electron',
  priority: 150, // Higher than CefSharp (100)
  detect: () => {
    return typeof window !== 'undefined' &&
           window.electron?.send !== undefined;
  },
  createTransport: () => new ElectronTransport(),
});

// Now auto-detection will check your custom transport first
const transport = detectTransport();
```

## API 参考

### 运输接口

所有传输系统实施的核心接口 :

```typescript
interface Transport {
  readonly name: string;
  isAvailable(): boolean;
  send(message: string): void;
  subscribe(listener: TransportListener): TransportUnsubscribe;
}
```

**属性 :**

-   `name` - 运输的唯一标识(例如“cefsharp”、“反应-内生”)

**方法:**

-   `isAvailable()` - 检查当前环境中是否有运输工具
-   `send(message: string)` - 向父/主机上下文发送信息
-   `subscribe(listener)` - 订阅收到的信件, 返回清理功能

### 类型

```typescript
// Message listener callback
type TransportListener = (message: string) => void;

// Cleanup function returned by subscribe
type TransportUnsubscribe = () => void;

// Factory function for creating transports
type TransportFactory = () => Transport;
```

### 传输检测器接口

用于登记海关运输:

```typescript
interface TransportDetector {
  readonly name: string;
  readonly priority: number;
  detect(): boolean;
  createTransport(): Transport;
}
```

**属性 :**

-   `name` - 运输标识符
-   `priority` - 检测优先级(先检查较高值)

**方法:**

-   `detect()` - 回来 `true` 如果有这种运输工具
-   `createTransport()` - 创建并返回运输实例

### 基础运输类

提供共同功能的抽象基础类:

```typescript
abstract class BaseTransport implements Transport {
  abstract readonly name: string;
  abstract isAvailable(): boolean;
  abstract send(message: string): void;
  abstract subscribe(listener: TransportListener): TransportUnsubscribe;

  protected hasWindow(): boolean;
  protected getWindow(): Window | null;
}
```

**受保护的助手 :**

-   `hasWindow()` - 检查是否 `window` 定义( SSR 安全)
-   `getWindow()` - 安全获取 `window` 对象或 `null`

### 运输登记

全球运输探测器管理登记册:

```typescript
class TransportRegistry {
  register(detector: TransportDetector): void;
  unregister(name: string): void;
  getDetectors(): readonly TransportDetector[];
  detect(forceRedetect?: boolean): Transport;
  clearCache(): void;
  reset(): void;
}
```

**方法:**

-   `register(detector)` - 登记海关运输探测器
-   `unregister(name)` - 取出一个名字的探测器
-   `getDetectors()` - 获取所有注册的探测器
-   `detect(forceRedetect?)` - 探测并返回适当的运输工具(密封)
-   `clearCache()` - 清除缓存运输工具
-   `reset()` - 重置为默认状态(仅装入探测器)

### 方便职能

```typescript
// Detect the current transport
function detectTransport(forceRedetect?: boolean): Transport;

// Register a custom detector
function registerTransport(detector: TransportDetector): void;
```

## 内建运输

### CefSharp 运输

用于使用桌面应用程序 [切夫共享](https://cefsharp.github.io/) (.NET的铬嵌入框架).

**检测 :** 检查 `window.CefSharp.PostMessage` **优先级 :** 100 (最高)

```typescript
import { CefSharpTransport } from '@aspectly/transports';

const transport = new CefSharpTransport();
transport.send(JSON.stringify({ action: 'openFile' }));

const unsubscribe = transport.subscribe((message) => {
  console.log('From C#:', message);
});
```

**通讯:**

-   通过 `window.CefSharp.PostMessage(message)`
-   通过 `window.postMessage` 事件

### WebKit 运输

对于在 Apple WKWebView (iOS, macOS, visionOS) 或 Linux WebKitGTK 内运行的网页内容 `WebKitWebView`。两者重复使用相同 `window.webkit.messageHandlers.aspectly` 机制.

**检测 :** 检查 `window.webkit.messageHandlers.aspectly` **优先级 :** 95 (韩语)

```typescript
import { WebKitTransport } from '@aspectly/transports';

const transport = new WebKitTransport();
transport.send(JSON.stringify({ action: 'openFile' }));
```

**通讯:**

-   通过 `window.webkit.messageHandlers.aspectly.postMessage(message)`
-   通过 `window.postMessage` 事件

### 反向运输

对于在内部运行的网络内容 [反应原生网络视频](https://github.com/react-native-webview/react-native-webview)。 。 。 .

**检测 :** 检查 `window.ReactNativeWebView.postMessage` **优先级 :** 90 (韩语)

```typescript
import { ReactNativeTransport } from '@aspectly/transports';

const transport = new ReactNativeTransport();
transport.send(JSON.stringify({ action: 'navigate' }));
```

**通讯:**

-   通过 `window.ReactNativeWebView.postMessage(message)`
-   信件被iOS兼容性的引文所包裹 : `'${message}'`
-   通过 `window.postMessage` 事件

### Android 运输公司

在Android内运行的网络内容 `WebView`。 。 。 .

**检测 :** 检查 `window.AspectlyAndroid.postMessage` **优先级 :** 85个

```typescript
import { AndroidTransport } from '@aspectly/transports';

const transport = new AndroidTransport();
transport.send(JSON.stringify({ action: 'navigate' }));
```

**通讯:**

-   通过 `window.AspectlyAndroid.postMessage(message)`
-   通过 `window.postMessage` 事件

### 小蝶运输

对于在小蝶内运行的网络内容 `webview_flutter` `WebViewController`。 。 。 .

**检测 :** 检查 `window.AspectlyFlutter.postMessage` **优先级 :** 84 (中文(简体) )

```typescript
import { FlutterTransport } from '@aspectly/transports';

const transport = new FlutterTransport();
transport.send(JSON.stringify({ action: 'navigate' }));
```

**通讯:**

-   通过 `window.AspectlyFlutter.postMessage(message)`
-   通过 `window.postMessage` 事件

### 框架运输

对于在iframe内运行的网络内容.

**检测 :** 检查是否 `window.parent !== window` **优先级 :** 80个

```typescript
import { IframeTransport } from '@aspectly/transports';

// Default: sends to any origin ('*')
const transport = new IframeTransport();

// Specify target origin for security
const secureTransport = new IframeTransport('https://parent-domain.com');

transport.send(JSON.stringify({ type: 'ready' }));
```

**构造器 :**

-   `new IframeTransport(targetOrigin?: string)` - 默认 : `'*'`

**通讯:**

-   通过 `window.parent.postMessage(message, targetOrigin)`
-   通过 `window.postMessage` 事件

### 窗口传输

在弹出窗口内运行的网络内容 `window.open`。 。 。 .

**检测 :** 检查是否 `window.opener !== null` **优先级 :** 70个

```typescript
import { WindowTransport } from '@aspectly/transports';

// Default: sends to any origin ('*')
const transport = new WindowTransport();

// Specify target origin for security
const secureTransport = new WindowTransport('https://opener-domain.com');

transport.send(JSON.stringify({ type: 'ready' }));
```

**构造器 :**

-   `new WindowTransport(targetOrigin?: string)` - 默认 : `'*'`

**通讯:**

-   通过 `window.opener.postMessage(message, targetOrigin)`
-   通过 `window.postMessage` 事件

### 邮政运输

常规 `window.postMessage` 之前用作后退运输 `NullTransport`。 。 。 .

**检测 :** 总是可用 **优先级 :** 10(最低不退缩)

```typescript
import { PostMessageTransport } from '@aspectly/transports';

const transport = new PostMessageTransport();
transport.send(JSON.stringify({ type: 'ready' }));
```

**通讯:**

-   通过 `window.postMessage(message, targetOrigin)`
-   通过 `window.postMessage` 事件

### 零运输

不进行操作的后退运输。 在没有其他运输工具时使用(例如,SSF、测试).

**优先级 :** 总是可用的( 回落)

```typescript
import { NullTransport } from '@aspectly/transports';

const transport = new NullTransport();
transport.isAvailable(); // true
transport.send('message'); // No-op (logs warning in development)
transport.subscribe(() => {}); // Returns no-op cleanup function
```

**行为:**

-   `isAvailable()` 总是返回 `true`
-   `send()` 是无( 开发模式下的日志警告)
-   `subscribe()` 返回一个不操作清理函数

## 子路径条目点

每个平台专用的运输也作为自己的子路径导出被曝光,因此可以仅导入您需要的运输而无需拉入其他运输:

| 入境点 | 出口 |
| --- | --- |
| `@aspectly/transports/webkit` | `WebKitTransport` |
| `@aspectly/transports/android` | `AndroidTransport` |
| `@aspectly/transports/flutter` | `FlutterTransport` |
| `@aspectly/transports/cefsharp` | `CefSharpTransport` |
| `@aspectly/transports/react-native` | `ReactNativeTransport` |
| `@aspectly/transports/iframe` | `IframeTransport` |
| `@aspectly/transports/window` | `WindowTransport` |

```typescript
import { WebKitTransport } from '@aspectly/transports/webkit';

const transport = new WebKitTransport();
```

软件包根( R)`@aspectly/transports`继续将每一运输连同登记和便利功能再出口.

## 创建自定义运输

### 示例:电子运输

```typescript
import { BaseTransport, registerTransport } from '@aspectly/transports';
import type { TransportListener, TransportUnsubscribe } from '@aspectly/transports';

// Extend BaseTransport for helper methods
class ElectronTransport extends BaseTransport {
  readonly name = 'electron';

  isAvailable(): boolean {
    const win = this.getWindow();
    return typeof win?.electron?.send === 'function';
  }

  send(message: string): void {
    const win = this.getWindow();
    if (!win?.electron?.send) {
      console.warn('[ElectronTransport] electron.send not available');
      return;
    }
    win.electron.send('message', message);
  }

  subscribe(listener: TransportListener): TransportUnsubscribe {
    const win = this.getWindow();
    if (!win?.electron?.on) {
      return () => {};
    }

    const handler = (_event: any, message: string) => {
      listener(message);
    };

    win.electron.on('message', handler);
    return () => {
      win.electron?.removeListener('message', handler);
    };
  }
}

// Register with high priority
registerTransport({
  name: 'electron',
  priority: 150,
  detect: () => {
    return typeof window !== 'undefined' &&
           window.electron?.send !== undefined;
  },
  createTransport: () => new ElectronTransport(),
});
```

### 执行情况核对表

创建自定义运输时 :

1.  扩展 `BaseTransport` 或执行 `Transport` 接口
2.  提供独有 `name` 属性
3.  执行 `isAvailable()` 检查环境
4.  执行 `send()` 发送信件
5.  执行 `subscribe()` 接收信件
6.  返回清理函数 `subscribe()`
7.  \* 处理安保部门改革/安全丢失全球
8.  创建一个 `TransportDetector` 登记
9.  设置适当 `priority` (较高=先检查)

## 相关软件包

-   [`@aspectly/core`](https://npmcn.com/package/%40aspectly/core) - 核心桥梁协议和信息处理
-   [`@aspectly/web`](https://npmcn.com/package/%40aspectly/web) - 网络/框架与反应钩的结合
-   [`@aspectly/react-native`](https://npmcn.com/package/%40aspectly/react-native) - 反应原生网络视频集成
-   [`@aspectly/react-native-web`](https://npmcn.com/package/%40aspectly/react-native-web) - 通用反应原生网络支持

## 许可证

麻省理工学院

## 常见问题

### @aspectly/transports 是什么？

视桥的运输层 - 站台检测和消息传递

### 如何安装 @aspectly/transports？

在项目目录运行 npm install @aspectly/transports，或使用 pnpm add / yarn add / bun add。

### @aspectly/transports 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @aspectly/transports 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @aspectly/transports 可以商用吗？

@aspectly/transports 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @aspectly/transports 的下载量有多少？

根据 npm 官方下载统计，@aspectly/transports 在 2026/10/07 – 2026/11/05 这 30 天内被下载 5,799 次，日均约 193 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @aspectly/transports 还在维护吗？

最新版本 2\.2\.0 发布于 2026/09/06（2 个月前）；至今共发布 12 个版本，其中过去 12 个月发布了 12 个；首次发布于 2026/03/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

