> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/zh/fa-bu/embedding/implementation/nodejs.md).

# Node.js/NPM

使用 NPM 包集成 Docs Embed，以获得完整的应用级控制

如果你需要更多控制并希望在应用层面进行操作，你可以从 npm 安装 GitBook embed 包。这种方式非常适合服务器端渲染、构建时集成或自定义 iframe 管理。

## 步骤

{% stepper %}
{% step %}
**安装该包**

添加 `@gitbook/embed` 到你的项目中：

```bash
npm install @gitbook/embed
```

如需完整的 API 参考和源代码，请查看 GitHub 上的 [`@gitbook/embed` 包](https://github.com/GitbookIO/gitbook/tree/main/packages/embed).
{% endstep %}

{% step %}
**导入该包**

在你的应用代码中，导入 `createGitBook` 函数：

```javascript
import { createGitBook } from "@gitbook/embed";
```

或者使用 CommonJS：

```javascript
const { createGitBook } = require("@gitbook/embed");
```

{% endstep %}

{% step %}
**初始化 GitBook**

使用你的文档站点 URL 创建一个 GitBook 实例：

```javascript
const gitbook = createGitBook({
  siteURL: "https://docs.company.com",
});
```

{% endstep %}

{% step %}
**创建一个 iframe**

生成一个 iframe 元素，并将其源设置为嵌入 URL：

```javascript
const iframe = document.createElement("iframe");
iframe.src = gitbook.getFrameURL({
  visitor: {
    token: 'your-jwt-token', // 可选：用于自适应内容或已认证访问
    unsignedClaims: { // 可选：用于动态表达式的自定义声明
      userId: '123',
      plan: 'premium'
    }
  }
});
iframe.id = "gitbook-embed-container";
iframe.style.border = "none";
iframe.style.width = "100%";
iframe.style.height = "600px";
iframe.allow = "clipboard-write";
```

{% hint style="info" %}
如果你使用 Assistant 标签页，请在 `allow="clipboard-write"` 上设置 iframe。NPM 包会将 iframe 的设置留给你。独立的 [Script 标签](/docs/documentation/zh/fa-bu/embedding/implementation/script.md) 实现会自动添加这一点。
{% endhint %}
{% endstep %}

{% step %}
**挂载该 frame**

创建一个 GitBook frame 实例并将其挂载到你的页面：

```javascript
const frame = gitbook.createFrame(iframe);
document.getElementById("gitbook-embed-container").appendChild(iframe);
```

{% endstep %}

{% step %}
**以编程方式控制嵌入内容**

使用 frame 实例与嵌入内容交互：

```javascript
// 导航到文档标签页中的特定页面
frame.navigateToPage("/getting-started");

// 切换到助手标签页
frame.navigateToAssistant();

// 向聊天发送一条消息
frame.postUserMessage("How do I get started?");

// 清除聊天记录
frame.clearChat();
```

{% endstep %}

{% step %}
**配置嵌入**

使用自定义选项配置嵌入：

```javascript
frame.configure({
  trademark: false,
  tabs: ['assistant', 'search', 'docs'],
  actions: [
    {
      icon: 'circle-question',
      label: '联系支持',
      onClick: () => window.open('https://support.example.com', '_blank')
    }
  ],
  greeting: { title: '欢迎！', subtitle: '我能帮你什么？' },
  assistantName: '支持副驾',
  closeButton: true,
  suggestions: ['What is GitBook?', 'How do I get started?'],
  tools: [/* ... */]
});
```

{% endstep %}

{% step %}
**监听事件**

注册事件监听器以响应嵌入事件：

```javascript
frame.on('close', () => {
  console.log('Frame 已关闭');
});

// 完成后取消订阅
const unsubscribe = frame.on('navigate', (data) => {
  console.log('Navigated to:', data.path);
});
```

{% endstep %}
{% endstepper %}

## API 参考

### 客户端工厂

* `createGitBook(options: { siteURL: string })` → `GitBookClient`
* `client.getFrameURL(options?: { visitor?: {...}, colorScheme?: 'light' | 'dark' })` → `字符串` - 获取带可选 frame 选项的 iframe URL
* `client.createFrame(iframe: HTMLIFrameElement)` → `GitBookFrameClient` - 创建一个 frame 客户端以与 iframe 通信

### Frame 客户端方法

* `frame.navigateToPage(path: string)` → `void` - 导航到文档标签页中的特定页面
* `frame.navigateToAssistant()` → `void` - 切换到助手标签页
* `frame.postUserMessage(message: string)` → `void` - 向聊天发送一条消息
* `frame.clearChat()` → `void` - 清除聊天记录
* `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void` - 配置嵌入
* `frame.on(event: string, listener: Function)` → `() => void` - 注册事件监听器（返回取消订阅函数）

## 配置选项

大多数自定义选项可通过 `frame.configure({...})`.

#### `tabs`

覆盖显示的标签页。

搜索默认启用。如果你设置 `tabs`，嵌入内容将只显示你列出的标签页。

* **类型**: `('assistant' | 'search' | 'docs')[]`

#### `操作`

在侧边栏中与标签页一起渲染的自定义操作按钮。每个操作按钮在点击时都会触发一个回调。

**注意**：这之前称为 `buttons`。请使用 `操作` 代替。

* **类型**: `Array<{ icon: string, label: string, onClick: () => void }>`

#### `问候语`

显示在 Assistant 标签页中的欢迎消息。

* **类型**: `{ title: string, subtitle: string }`

#### `assistantName`

覆盖 UI 中显示的助手名称。

* **类型**: `字符串`
* **最大长度**: `32` 字符

#### `closeButton`

在 Assistant 内部显示关闭按钮。

* **类型**: `boolean`

#### `建议`

显示在 Assistant 欢迎屏幕中的建议问题。

* **类型**: `string[]`

#### `商标`

在嵌入 UI 中显示或隐藏 GitBook 商标——包括 Docs Embed 页脚和 Assistant 品牌标识。

* **类型**: `boolean`
* **默认**: `true`

#### `工具`

用于扩展 Assistant 的自定义 AI 工具。详情请参见 [创建自定义工具](/docs/documentation/zh/fa-bu/embedding/configuration/creating-custom-tools.md) 。

* **类型**: `Array<{ name: string, description: string, inputSchema: object, execute: Function, confirmation?: {...} }>`

### Frame URL 选项

某些选项会传递给 `getFrameURL({...})`.

#### `colorScheme`

覆盖嵌入的配色方案。

如果省略，嵌入将遵循 iframe 的 CSS `color-scheme`，从而继承父页面或浏览器偏好。

* **类型**: `'light' | 'dark'`

### `visitor` （已认证访问）

传递给 `getFrameURL({ visitor: {...} })`。用于 [自适应内容](/docs/documentation/zh/fa-bu/adaptive-content.md) 以及 [已认证访问](/docs/documentation/zh/fa-bu/site-audience/authenticated-access.md).

* **类型**: `{ token?: string, unsignedClaims?: Record<string, unknown> }`

## 常见陷阱

* **忘记安装该包** – 运行 `npm install @gitbook/embed` 后再导入。
* **缺少 siteURL** –  `siteURL` 选项是必需的，并且必须与你已发布的文档站点匹配。
* **iframe 未渲染** – 确保父容器具有足够的宽度/高度以显示 iframe。
* **在初始化前调用 Frame 方法** – 等待直到 `createFrame()` 完成后再调用 frame 方法。
* **未取消事件订阅** – 记得调用由 `frame.on()` 返回的取消订阅函数，以防止内存泄漏。
* **使用旧版 API 方法** – 类似于 `open()`, `close()`, `toggle()`，以及 `destroy()` 的方法在 NPM 包中不可用。请改用 frame 客户端方法。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://gitbook.com/docs/documentation/zh/fa-bu/embedding/implementation/nodejs.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
