> 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 安装 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 的设置留给你。独立的 [Script 标签](/docs/documentation/zh/fa-bu/embedding/implementation/script.md) 实现会自动添加这一项。
{% endhint %}
{% endstep %}

{% step %}
**挂载框架**

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

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

{% endstep %}

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

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

```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` - 切换到 Assistant 选项卡
* `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`

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

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

#### `assistantName`

覆盖 UI 中显示的 assistant 名称。

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

#### `closeButton`

在 Assistant 内部显示一个关闭按钮。

* **类型**: `boolean`

#### `suggestions`

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

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

#### `trademark`

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

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

#### `tools`

用于扩展 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.
