> 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/publish/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 选项卡，请在 iframe 上设置 `allow="clipboard-write"` 。NPM 软件包需要您自行设置 iframe。独立的 [脚本标签](https://gitbook.com/docs/documentation/zh/publish/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 closed');
});

// 完成后取消订阅
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' })` → `string` - 获取 iframe URL，可选择指定框架选项
* `client.createFrame(iframe: HTMLIFrameElement)` → `GitBookFrameClient` - 创建框架客户端，以便与 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')[]`

#### `actions`

在侧边栏中与选项卡一同呈现的自定义操作按钮。点击每个操作按钮时都会触发回调。

**注意**：此选项之前名为 `buttons`。请改用 `actions` 。

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

#### `greeting`

显示在助手选项卡中的欢迎消息。

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

#### `assistantName`

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

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

#### `closeButton`

在助手中显示关闭按钮。

* **类型**: `boolean`

#### `suggestions`

显示在助手欢迎界面中的建议问题。

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

#### `trademark`

显示或隐藏嵌入式 UI 中的 GitBook 商标，包括 Docs Embed 页脚和助手品牌标识。

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

#### `tools`

用于扩展 Assistant 的自定义 AI 工具。详情请参阅 [创建自定义工具](https://gitbook.com/docs/documentation/zh/publish/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: {...} })`。用于 [自适应内容](https://gitbook.com/docs/documentation/zh/publish/adaptive-content.md) 和 [经过身份验证的访问](https://gitbook.com/docs/documentation/zh/publish/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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook.com/docs/documentation/zh/publish/embedding/implementation/nodejs.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
