> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# Lynxtron 中 Node.js 与 Lynx 的通信

如果你熟悉 Electron，可以先把 Lynxtron 中的通信需求理解为两类：

1. **Node 主进程与 UI 双向消息通信**：类似 Electron 中主进程与 [`BrowserWindow`](https://www.electronjs.org/zh/docs/latest/api/browser-window) renderer 之间的 IPC。
2. **在 UI 中直接使用 Node.js 能力**：Electron 技术上支持通过 [`nodeIntegration`](https://www.electronjs.org/zh/docs/latest/api/browser-window#new-browserwindowoptions) 在 Web 中直接调用 Node.js 能力，但通常不推荐直接开启；Lynxtron 则通过增强 [preload scripts](#使用-preload-scripts)，使其能在隔离 context 中使用 Node.js，并将 JS 对象暴露给 Lynx UI 调用。

Lynxtron 对这两类需求分别提供了对应能力：

- 使用 `NativeModules.bridge` 通道，配合主进程侧的 `lynxBridge`（`lynxBridge.handle()` 处理需要回调的调用，`lynxBridge.on()` 处理单向消息）和 [`LynxWindow.sendGlobalEvent()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md#sendglobalevent) 实现 Node 主进程与 Lynx 的通信。
- 使用 Lynxtron [preload scripts](#使用-preload-scripts)，在 preload script 中通过 [`contextBridge.exposeInLynxBTS()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/context-bridge/Interface.ContextBridge.md#exposeinlynxbts) 将 Node.js 的 JS 对象暴露给 Lynx UI 中的 [`NativeModules.nodejs.exposed`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md#exposed) 对象。

## 和 Electron 的能力对照

| 需求                  | Electron                                                                                                                                                                                                                                                                                                                                           | Lynxtron                                                                                                                                                                                                                                                                                                                                                              |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| UI 使用 Node.js 能力    | [preload scripts](https://www.electronjs.org/zh/docs/latest/tutorial/tutorial-preload) / [`contextBridge.exposeInMainWorld()`](https://www.electronjs.org/zh/docs/latest/api/context-bridge#contextbridgeexposeinmainworldapikey-api) / [`nodeIntegration`](https://www.electronjs.org/zh/docs/latest/api/browser-window#new-browserwindowoptions) | [`lynxPreference.preload`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Interface.LynxPreference.md#preload) + [`contextBridge.exposeInLynxBTS()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/context-bridge/Interface.ContextBridge.md#exposeinlynxbts) + [`NativeModules.nodejs.exposed`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md#exposed) |
| Node 主进程向 UI 推送消息   | [`webContents.send()`](https://www.electronjs.org/zh/docs/latest/api/web-contents#contentssendchannel-args)                                                                                                                                                                                                                                        | [`LynxWindow.sendGlobalEvent()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md#sendglobalevent)                                                                                                                                                                                                                                                         |
| UI 调用 Node 主进程并等待结果 | [`ipcRenderer.invoke()`](https://www.electronjs.org/zh/docs/latest/api/ipc-renderer#ipcrendererinvokechannel-args) + [`ipcMain.handle()`](https://www.electronjs.org/zh/docs/latest/api/ipc-main#ipcmainhandlechannel-listener)                                                                                                                    | `NativeModules.bridge.call()` + `lynxBridge.handle()`                                                                                                                                                                                                                                                                                                                 |
| UI 向 Node 主进程发送单向消息 | [`ipcRenderer.send()`](https://www.electronjs.org/zh/docs/latest/api/ipc-renderer#ipcrenderersendchannel-args) + [`ipcMain.on()`](https://www.electronjs.org/zh/docs/latest/api/ipc-main#ipcmainonchannel-listener)                                                                                                                                | `NativeModules.bridge.send()` + `lynxBridge.on()`                                                                                                                                                                                                                                                                                                                     |

## 使用 Preload Scripts

Lynxtron 的 [preload scripts](#使用-preload-scripts) 可以理解为 [Electron preload scripts](https://www.electronjs.org/zh/docs/latest/tutorial/tutorial-preload) / [`contextBridge`](https://www.electronjs.org/zh/docs/latest/api/context-bridge) 模式面向 Lynx BTS 的能力增强：preload script 可以直接使用 Node.js API，并把方法或对象暴露给 Lynx UI 调用。

Electron 中，preload script 与 Web 页面处于隔离的 JS context；preload script 与 Web 最终需要通过 [`contextBridge`](https://www.electronjs.org/zh/docs/latest/api/context-bridge) 或 IPC 做跨 context 的序列化/代理通信，Web 侧不能直接使用 preload script context 中的原始 JS 对象。

Lynxtron 中，Lynx BTS 与 preload scripts 都运行在 Node.js 中，但处于隔离的 JS context；preload script context 有 Node.js 能力，可以通过 [`contextBridge.exposeInLynxBTS()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/context-bridge/Interface.ContextBridge.md#exposeinlynxbts) 将 JS 对象暴露给 Lynx BTS 直接访问。

### 配置 preload scripts

创建窗口时，通过 [`lynxPreference.preload`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Interface.LynxPreference.md#preload) 指定 preload script 文件：

```typescript
// main.ts
import { app, LynxWindow } from '@lynx-js/lynxtron';
import path from 'path';

app.whenReady().then(() => {
  const win = new LynxWindow({
    width: 800,
    height: 600,
    lynxPreference: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  win.loadFile('main.lynx.bundle');
});
```

### 在 preload script 中暴露 Node.js API

preload script 中可以直接使用 Node.js API，然后通过 [`contextBridge.exposeInLynxBTS()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/context-bridge/Interface.ContextBridge.md#exposeinlynxbts) 暴露给 Lynx：

```typescript
// preload.ts
import { contextBridge } from '@lynx-js/lynxtron/context-bridge';
import fs from 'fs';
import path from 'path';

type ExposedNodeApi = {
  readTextFileWithTransform: (
    filePath: string,
    transform: (content: string) => string,
  ) => Promise<string>;
  createReader: (baseDir: string) => {
    read: (relativePath: string) => Promise<string>;
  };
};

const nodeApi: ExposedNodeApi = {
  readTextFileWithTransform: async (filePath, transform) => {
    const content = await fs.promises.readFile(filePath, 'utf8');
    return transform(content);
  },

  createReader: (baseDir: string) => {
    return {
      read: (relativePath: string) => {
        return fs.promises.readFile(path.join(baseDir, relativePath), 'utf8');
      },
    };
  },
};

contextBridge.exposeInLynxBTS(nodeApi);
```

### 在 Lynx 中调用暴露的 API

Lynx BTS 通过 [`NativeModules.nodejs.exposed`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md#exposed) 访问这些 API：

暴露的 JS 对象可以包含函数；函数的入参也可以是函数；函数可以使用 preload script context 中的闭包，也可以返回 Promise。Lynx UI 侧按普通异步 JS API 调用即可。

```tsx
// App.tsx
const api = NativeModules.nodejs.exposed;

const title = await api.readTextFileWithTransform(
  '/Users/example/notes.txt',
  (text) => text.split('\n')[0],
);

const reader = api.createReader('/Users/example');
const todo = await reader.read('todo.txt');
```

### 示例：文件浏览器

这个示例演示在 Lynx UI 中使用 preload script 暴露的 Node.js 能力：

- preload script 通过 [`contextBridge.exposeInLynxBTS()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/context-bridge/Interface.ContextBridge.md#exposeinlynxbts) 暴露 `readdir`、`homedir` 等 API。
- Lynx UI 通过 [`NativeModules.nodejs.exposed`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md#exposed) 调用这些 API，实现目录浏览和文件内容查看。


**下面是一个示例: file-explorer**

**Bundle:** `dist/desktop/main.lynx.bundle`

```tsx
import { useState, useEffect } from '@lynx-js/react';
import '@lynxtron-examples/config/tokens.css';
import './App.css';

interface DirEntry {
  name: string;
  isDirectory: boolean;
  isFile: boolean;
  path: string;
}

export function App() {
  const [currentPath, setCurrentPath] = useState('');
  const [entries, setEntries] = useState<DirEntry[]>([]);
  const [selectedFile, setSelectedFile] = useState<string | null>(null);
  const [fileContent, setFileContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadDirectory = async (dirPath: string) => {
    setLoading(true);
    setError(null);
    try {
      const api = NativeModules.nodejs.exposed;
      const dirEntries = await api.readdir(dirPath);
      setEntries(dirEntries.sort((a, b) => {
        if (a.isDirectory && !b.isDirectory) return -1;
        if (!a.isDirectory && b.isDirectory) return 1;
        return a.name.localeCompare(b.name);
      }));
      setCurrentPath(dirPath);
    } catch (err: any) {
      setError(`Error loading directory: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  const goHome = () => {
    const api = NativeModules.nodejs.exposed;
    loadDirectory(api.homedir());
  };

  const goUp = () => {
    const api = NativeModules.nodejs.exposed;
    const parent = api.dirname(currentPath);
    if (parent !== currentPath) {
      loadDirectory(parent);
    }
  };

  const openEntry = async (entry: DirEntry) => {
    if (entry.isDirectory) {
      loadDirectory(entry.path);
    } else {
      setLoading(true);
      setError(null);
      try {
        const api = NativeModules.nodejs.exposed;
        const content = await api.readFile(entry.path);
        setSelectedFile(entry.path);
        setFileContent(content);
      } catch (err: any) {
        setError(`Error reading file: ${err.message}`);
      } finally {
        setLoading(false);
      }
    }
  };





  useEffect(() => {
    goHome();
  }, []);

  if (selectedFile) {
    const api = NativeModules.nodejs.exposed;
    return (
      <view className="container">
        <view className="header">
          <text className="title" text-maxline="1">{api.basename(selectedFile)}</text>
          <view className="back-button" bindtap={() => setSelectedFile(null)}>
            <text className="button-text">Back</text>
          </view>
        </view>
        <scroll-view scroll-y className="file-content">
          <text className="content-text">{fileContent}</text>
        </scroll-view>
        {error && <text className="error">{error}</text>}
      </view>
    );
  }

  return (
    <view className="container">
      <view className="header">
        <text className="title">File Explorer</text>
        <view className="nav-buttons">
          <view className="nav-button" bindtap={goHome}>
            <text className="button-text">Home</text>
          </view>
          <view className="nav-button" bindtap={goUp}>
            <text className="button-text">Up</text>
          </view>
        </view>
      </view>
      <view className="path-bar">
        <text className="path-text" text-maxline="1">{currentPath}</text>
      </view>
      <scroll-view scroll-y className="file-list">
        {loading && <text className="loading">reading dir…</text>}
        {entries.map((entry) => (
          <view
            key={entry.path}
            className={`list-item ${entry.isDirectory ? 'directory' : 'file'}`}
            bindtap={() => openEntry(entry)}
          >
            <text className="item-name" text-maxline="1">{entry.name}</text>
            <text className="item-kind">{entry.isDirectory ? 'folder' : 'file'}</text>
          </view>
        ))}
      </scroll-view>
      {error && <text className="error">{error}</text>}
    </view>
  );
}

```



## Node 主进程与 Lynx 双向消息通信

这种方式适合窗口控制、系统服务、数据库访问、主进程状态管理等场景。Node.js 能力保留在主进程，Lynx 通过消息调用。

### Node.js 向 Lynx 推送消息

Node 主进程可以通过 [`LynxWindow.sendGlobalEvent()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md#sendglobalevent) 主动向 Lynx 发送事件：

```typescript
// main.ts
// 复用 app.whenReady() 内创建的窗口，并在 UI 注册监听器后发送。
win.sendGlobalEvent('systemInfoUpdate', {
  cpuUsage: 32,
  memoryUsage: 68,
});
```

Lynx 侧通过 [`GlobalEventEmitter`](/next/zh/guide/interaction/event-handling/event-propagation.md#globaleventemitter) 监听事件：

```tsx
// App.tsx
import { useEffect, useState } from '@lynx-js/react';

export function App() {
  const [systemInfo, setSystemInfo] = useState(null);

  useEffect(() => {
    const emitter = lynx.getJSModule('GlobalEventEmitter');
    const handleUpdate = (data) => {
      setSystemInfo(data);
    };

    emitter.addListener('systemInfoUpdate', handleUpdate);
    return () => {
      emitter.removeListener('systemInfoUpdate', handleUpdate);
    };
  }, []);

  return <view>{/* render systemInfo */}</view>;
}
```

### Lynx 调用 Node.js 并等待返回值

`bridge.call(method, payload, callback)` 返回 `void`，结果通过第三个参数回调返回，不能直接 `await bridge.call(...)`。需要使用 `await` 时，请像 System Monitor 示例一样用 Promise 包装回调。

```tsx
// App.tsx
NativeModules.bridge.call(
  'getSystemInfo',
  { includeCpuDetail: true },
  (info) => {
    setSystemInfo(info);
  },
);
```

Node 主进程通过 `lynxBridge.handle()` 注册处理器来响应 `bridge.call` 调用。handler 的返回值（或返回的 Promise）会自动通过 `event.sendReply` 回传给 Lynx，行为等同于 Electron 中的 `ipcMain.handle()`：

```typescript
// main.ts
import { app, lynxBridge } from '@lynx-js/lynxtron';

app.whenReady().then(() => {
  lynxBridge.handle('getSystemInfo', (event, params) => {
    return getSystemInfo(params);
  });
});
```

对于异步逻辑，请返回一个 Promise，让运行时在 Promise resolve 后自动回复。**不要在通过 `handle` 注册的处理器中手动调用 `event.sendReply()`**：运行时已经会用 handler 的返回值调用一次 `sendReply`，再显式调用一次会产生重复回复。

```typescript
lynxBridge.handle('getSystemInfo', (event, params) => {
  return new Promise<SystemInfo>((resolve) => {
    fetchAsync(params, resolve);
  });
});
```

### Lynx 向 Node.js 发送单向消息

通过 `bridge.send` 通知 Node.js（单向通知，不需要返回值）。

```tsx
// App.tsx
NativeModules.bridge.send('refreshIntervalChanged', { interval: 1000 });
```

Node 主进程通过 `lynxBridge` 上监听消息（它本身就是一个 Node.js `EventEmitter`），行为等同于 Electron 中的 `ipcMain.on()`：

```typescript
// main.ts
import { app, lynxBridge } from '@lynx-js/lynxtron';

app.whenReady().then(() => {
  lynxBridge.on('refreshIntervalChanged', (params) => {
    console.log('refresh interval:', params.interval);
  });
});
```

### `lynxBridge` API

`lynxBridge` 是从 `@lynx-js/lynxtron` 导入的主进程单例，它是一个 Node.js `EventEmitter`，除下列 invoke 相关方法外，还可以使用 `on` / `once` / `off` / `emit` 等标准方法。在 Electron 中，`lynxBridge` 相当于 `ipcMain`。

| 方法                                       | 说明                                                                                                                      |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `lynxBridge.handle(method, handler)`     | 为 `NativeModules.bridge.call(method, args, callback)` 注册处理器。handler 的返回值（或返回的 Promise）会自动回传给 Lynx。同一个 `method` 重复注册会抛错。 |
| `lynxBridge.handleOnce(method, handler)` | 与 `handle` 相同，但 handler 触发一次后会自动移除。                                                                                     |
| `lynxBridge.removeHandler(method)`       | 移除通过 `handle` / `handleOnce` 注册的处理器。                                                                                    |
| `lynxBridge.on(channel, listener)`       | 继承自 `EventEmitter`。用于接收 Lynx 通过 `NativeModules.bridge.send(channel, args)` 发送的单向消息，listener 的入参为 `(args)`。              |

`handler` 的签名为 `(event: LynxBridgeInvokeEvent, args) => unknown | Promise<unknown>`。运行时会用 handler 的返回值（在 Promise 场景下为其 resolve 后的值）自动调用一次 [`event.sendReply()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Interface.LynxBridgeInvokeEvent.md)，因此通过 `handle` / `handleOnce` 注册的处理器应当通过返回值（或 Promise）表达回复内容；再显式调用 `event.sendReply()` 会产生重复回复。`sendReply` 仅供直接监听底层 invoke 事件、绕过 `handle` 包装的低层调用者使用。

### 示例：系统资源监控面板

这个示例演示 Node 主进程与 Lynx 的双向消息通信：

- Node.js 端使用 `os` 模块获取 CPU、内存等系统信息，并通过 [`LynxWindow.sendGlobalEvent()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md#sendglobalevent) 推送给 Lynx。
- Lynx 端通过 [`GlobalEventEmitter`](/next/zh/guide/interaction/event-handling/event-propagation.md#globaleventemitter) 接收更新，也可以通过 `NativeModules.bridge.call()` 主动请求最新数据。
- 刷新间隔变化这类不需要返回值的通知，可以通过 `NativeModules.bridge.send()` 发送给 Node 主进程。


**下面是一个示例: system-monitor**

**Bundle:** `dist/desktop/main.lynx.bundle`

```tsx
import { useState, useEffect, useCallback } from '@lynx-js/react';
import '@lynxtron-examples/config/tokens.css';
import './App.css';

interface SystemInfo {
  cpuUsage: number;
  memoryUsage: number;
  totalMemory: number;
  freeMemory: number;
  platform: string;
  arch: string;
  uptime: number;
}

declare const NativeModules: {
  bridge: {
    call: (method: 'getSystemInfo', data: object, callback: (info: SystemInfo) => void) => void;
    send: (method: string, data?: any) => void;
  };
};

declare const GlobalEventEmitter: {
  addListener: (event: string, callback: (data: any) => void) => void;
  removeListener: (event: string, callback: (data: any) => void) => void;
};

export function App() {
  const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
  const [refreshInterval, setRefreshInterval] = useState(1000);
  const [isLoading, setIsLoading] = useState(true);

  const loadSystemInfo = useCallback(async () => {
    try {
      const info = await new Promise<SystemInfo>((resolve) => {
        NativeModules.bridge.call('getSystemInfo', {}, resolve);
      });
      setSystemInfo(info);
      setIsLoading(false);
    } catch (error) {
      console.error('Error loading system info:', error);
    }
  }, []);

  const handleSetInterval = useCallback((interval: number) => {
    setRefreshInterval(interval);
    NativeModules.bridge.send('setRefreshInterval', { interval });
  }, []);

  const formatUptime = (seconds: number): string => {
    const days = Math.floor(seconds / 86400);
    const hours = Math.floor((seconds % 86400) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    return `${days}d ${hours}h ${minutes}m ${secs}s`;
  };

  useEffect(() => {
    loadSystemInfo();

    const handleSystemInfoUpdate = (data: SystemInfo) => {
      setSystemInfo(data);
      setIsLoading(false);
    };

    lynx.getJSModule('GlobalEventEmitter').addListener('systemInfoUpdate', handleSystemInfoUpdate);

    return () => {
      lynx.getJSModule('GlobalEventEmitter').removeListener('systemInfoUpdate', handleSystemInfoUpdate);
    };
  }, [loadSystemInfo]);

  if (isLoading) {
    return (
      <view className="container">
        <text className="body-text">Loading system data…</text>
      </view>
    );
  }

  return (
    <view className="container">
      <text className="app-title">System Monitor</text>

      <view className="panel">
        <text className="panel-title">Processor</text>
        <text className="metric-value">{systemInfo?.cpuUsage.toFixed(1)}%</text>
        <view className="progress-track">
          <view
            className="progress-fill"
            style={{ width: `${Math.min(systemInfo?.cpuUsage || 0, 100)}%` }}
          />
        </view>
      </view>

      <view className="panel">
        <text className="panel-title">Memory</text>
        <text className="metric-value">{systemInfo?.memoryUsage.toFixed(1)}%</text>
        <view className="progress-track">
          <view
            className="progress-fill"
            style={{ width: `${Math.min(systemInfo?.memoryUsage || 0, 100)}%` }}
          />
        </view>
        <view className="info-row">
          <text className="info-key">Total</text>
          <text className="info-value">{systemInfo?.totalMemory.toFixed(2)} GB</text>
        </view>
        <view className="info-row">
          <text className="info-key">Free</text>
          <text className="info-value">{systemInfo?.freeMemory.toFixed(2)} GB</text>
        </view>
      </view>

      <view className="panel">
        <text className="panel-title">System</text>
        <view className="info-row">
          <text className="info-key">Platform</text>
          <text className="info-value">{systemInfo?.platform}</text>
        </view>
        <view className="info-row">
          <text className="info-key">Architecture</text>
          <text className="info-value">{systemInfo?.arch}</text>
        </view>
        <view className="info-row">
          <text className="info-key">Uptime</text>
          <text className="info-value">{systemInfo ? formatUptime(systemInfo.uptime) : ''}</text>
        </view>
      </view>

      <view className="panel">
        <text className="panel-title">Refresh interval</text>
        <view className="interval-buttons">
          <view
            className={`interval-button ${refreshInterval === 500 ? 'active' : ''}`}
            bindtap={() => handleSetInterval(500)}
          >
            <text className="interval-button-text">500ms</text>
          </view>
          <view
            className={`interval-button ${refreshInterval === 1000 ? 'active' : ''}`}
            bindtap={() => handleSetInterval(1000)}
          >
            <text className="interval-button-text">1s</text>
          </view>
          <view
            className={`interval-button ${refreshInterval === 2000 ? 'active' : ''}`}
            bindtap={() => handleSetInterval(2000)}
          >
            <text className="interval-button-text">2s</text>
          </view>
          <view
            className={`interval-button ${refreshInterval === 5000 ? 'active' : ''}`}
            bindtap={() => handleSetInterval(5000)}
          >
            <text className="interval-button-text">5s</text>
          </view>
        </view>
      </view>
    </view>
  );
}

```



## 能力参考

| 能力                                        | API                                                                                                                                    |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| 配置窗口级 preload script                      | [`lynxPreference.preload`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Interface.LynxPreference.md#preload)                                |
| 从 preload scripts 向 Lynx 暴露 Node.js 方法或对象 | [`contextBridge.exposeInLynxBTS()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/context-bridge/Interface.ContextBridge.md#exposeinlynxbts) |
| 从 Lynx UI 调用 preload scripts 暴露的方法或对象     | [`NativeModules.nodejs.exposed`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md#exposed)                     |
| 从 Node 主进程向 Lynx 推送事件                     | [`LynxWindow.sendGlobalEvent()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md#sendglobalevent)                          |
| 从 Lynx 调用 Node 主进程并等待返回值                  | `NativeModules.bridge.call` → `lynxBridge.handle()`                                                                                    |
| 从 Lynx 向 Node 主进程发送单向消息                   | `NativeModules.bridge.send` → `lynxBridge.on()`                                                                                        |

## 为什么 Lynxtron 这样设计

Lynxtron 用两条通道覆盖 Electron 中常见的两类能力，因为它们解决的问题不同：

- [`NativeModules.nodejs.exposed`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md#exposed)：Lynx BTS 直接访问 preload scripts 暴露的 JS 对象，对应通过 [Electron preload scripts](https://www.electronjs.org/zh/docs/latest/tutorial/tutorial-preload) / [`nodeIntegration`](https://www.electronjs.org/zh/docs/latest/api/browser-window#new-browserwindowoptions) 在 UI 中使用 Node.js 能力。
- `NativeModules.bridge` + `lynxBridge`：Lynx 与 Node 主进程之间的消息通信，对应 Electron 的 `ipcRenderer` ↔ `ipcMain` IPC。

关键差异不是 API 挂在哪个全局对象上，而是 Lynxtron 为 Lynx BTS 提供了一条 JS 对象暴露路径。

## API 与规范

| API / 规范                                                                                                                               | 说明                                                                                                     |
| -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| [`LynxWindow`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md)                                                            | 创建窗口、加载 Lynx bundle                                                                                    |
| [`LynxWindowConstructorOptions`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Interface.LynxWindowConstructorOptions.md)                    | 配置 `lynxPreference` 等窗口参数                                                                              |
| [`contextBridge.exposeInLynxBTS()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/context-bridge/Interface.ContextBridge.md#exposeinlynxbts) | 从 preload script 向 Lynx BTS 暴露 JS 对象                                                                   |
| [`LynxWindow.sendGlobalEvent()`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md#sendglobalevent)                          | Node 主进程向 Lynx 推送全局事件                                                                                  |
| [`lynxBridge`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Variable.lynxBridge.md)                                                         | 主进程单例，用于处理来自 Lynx 的 `bridge.call` / `bridge.send`                                                      |
| [`LynxBridge`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Interface.LynxBridge.md)                                                        | `lynxBridge` 的接口类型，提供 `handle` / `handleOnce` / `removeHandler`，并继承 `EventEmitter` API                 |
| [`LynxBridgeInvokeEvent`](/next/zh/lynxtron/api/@lynx-js/lynxtron/Interface.LynxBridgeInvokeEvent.md)                                  | `lynxBridge.handle()` 回调收到的事件对象，提供 `sendReply()`                                                       |
| [`LynxtronNodejs`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md)                                           | [`NativeModules.nodejs`](/next/zh/lynxtron/api/@lynx-js/lynxtron/lynx/Interface.LynxtronNodejs.md) 的类型 |
| [`GlobalEventEmitter`](/next/zh/guide/interaction/event-handling/event-propagation.md#globaleventemitter)                              | Lynx BTS 中监听全局事件                                                                                       |
| [`lynx.getJSModule()`](/next/zh/api/lynx-api/lynx/lynx-get-js-module.md)                                                               | 获取 `GlobalEventEmitter` 等模块                                                                            |
