> 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/docs-site/embedding/implementation/nodejs.md).

# Node.js/NPM

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

## 步骤

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

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

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

有关完整的 API 参考和源代码，请查看 [`@gitbook/embed` GitHub 上的包](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 tag](/docs/documentation/zh/docs-site/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");

// 切换到 Assistant 选项卡
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: 'Contact Support',
      onClick: () => window.open('https://support.example.com', '_blank')
    }
  ],
  greeting: { title: 'Welcome!', subtitle: 'How can I help?' },
  assistantName: 'Support Copilot',
  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` - 获取带有可选 frame 参数的 iframe URL
* `client.createFrame(iframe: HTMLIFrameElement)` → `GitBookFrameClient` - 创建一个用于与 iframe 通信的 frame 客户端

### 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 中显示的助手名称。

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

#### `closeButton`

在 Assistant 内显示关闭按钮。

* **类型**: `boolean`

#### `suggestions`

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

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

#### `trademark`

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

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

#### `tools`

用于扩展 Assistant 的自定义 AI 工具。详情请参见 [创建自定义工具](/docs/documentation/zh/docs-site/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/zhan-dian-fang-wen-quan-xian/adaptive-content.md) 和 [已认证访问](/docs/documentation/zh/zhan-dian-fang-wen-quan-xian/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/docs-site/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.
