> 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/configuration/reference.md).

# API 参考

了解以编程方式使用 Docs Embed 时可用的方法

Docs Embed 会根据集成方式提供不同的 API。本参考介绍了各种集成方式中所有可用的方法。

## 方法对比

| 方法           | 独立脚本                                                         | NPM 包                                 | React 组件                             |
| ------------ | ------------------------------------------------------------ | ------------------------------------- | ------------------------------------ |
| **初始化**      | `GitBook('init', options, frameOptions)`                     | `createGitBook(options)`              | `<GitBookProvider siteURL="...">`    |
| **覆盖配色方案**   | `GitBook('init', options, { colorScheme })`                  | `client.getFrameURL({ colorScheme })` | `<GitBookFrame colorScheme="..." />` |
| **获取框架 URL** | ❌（内部处理）                                                      | `client.getFrameURL(options)`         | `useGitBook().getFrameURL(options)`  |
| **创建框架客户端**  | ❌（内部处理）                                                      | `client.createFrame(iframe)`          | `useGitBook().createFrame(iframe)`   |
| **显示/隐藏小组件** | `GitBook('show')` / `GitBook('hide')`                        | ❌                                     | ❌                                    |
| **打开/关闭窗口**  | `GitBook('open')` / `GitBook('close')` / `GitBook('toggle')` | ❌                                     | ❌                                    |
| **导航到页面**    | `GitBook('navigateToPage', path)`                            | `frame.navigateToPage(path)`          | 通过框架客户端                              |
| **导航到助手**    | `GitBook('navigateToAssistant')`                             | `frame.navigateToAssistant()`         | 通过框架客户端                              |
| **发送消息**     | `GitBook('postUserMessage', message)`                        | `frame.postUserMessage(message)`      | 通过框架客户端                              |
| **清除聊天记录**   | `GitBook('clearChat')`                                       | `frame.clearChat()`                   | 通过框架客户端                              |
| **配置**       | `GitBook('configure', settings)`                             | `frame.configure(settings)`           | 上的属性 `<GitBookFrame>`                |
| **事件监听器**    | ❌                                                            | `frame.on(event, listener)`           | 通过框架客户端                              |
| **卸载**       | `GitBook('unload')`                                          | ❌                                     | ❌                                    |

## 独立脚本 API

### 初始化

#### `GitBook('init', options, frameOptions)`

使用站点 URL 和可选的已验证访问权限初始化小组件。

**参数：**

* `options`: `{ siteURL: string }` - GitBook 文档站点的 URL
* `frameOptions`: `{ visitor?: { token?: string, unsignedClaims?: Record<string, unknown> }, colorScheme?: 'light' | 'dark' }` （可选）- 框架选项

**示例：**

```javascript
window.GitBook('init', 
  { siteURL: 'https://docs.company.com' },
  { visitor: { token: 'your-jwt-token' }, colorScheme: 'dark' }
);
```

省略时， `colorScheme` 将遵循 iframe 的 CSS `color-scheme`.

### 小组件控制

#### 显示小组件

如果 GitBook 小组件处于隐藏状态，则将其显示出来。

**示例：**

```js
window.GitBook("show");
```

#### 隐藏小组件

隐藏 GitBook 小组件，但不卸载它。

**示例：**

```js
window.GitBook("hide");
```

#### 打开窗口

打开 Docs Embed 窗口。

**示例：**

```js
window.GitBook("open");
```

#### 关闭窗口

关闭 Docs Embed 窗口。

**示例：**

```js
window.GitBook("close");
```

#### 切换窗口状态

切换 Docs Embed 窗口的打开或关闭状态。

**示例：**

```js
window.GitBook("toggle");
```

#### 卸载小组件

从你的站点中彻底移除 GitBook 小组件。

**示例：**

```js
window.GitBook("unload");
```

### 导航

#### `GitBook('navigateToPage', path)`

根据路径导航到 GitBook 文档中的指定页面。

**参数：**

* `path` （字符串）：要导航到的页面路径

**示例：**

```javascript
// 导航到入门指南
window.GitBook("navigateToPage", "/getting-started");

// 导航到指定的 API 文档页面
window.GitBook("navigateToPage", "/api/authentication");

// 导航到常见问题部分
window.GitBook("navigateToPage", "/faq/billing");
```

#### `GitBook('navigateToAssistant')`

直接导航到 Assistant 选项卡。

**示例：**

```javascript
// 切换至助手选项卡
window.GitBook("navigateToAssistant");

// 你可以在按钮点击事件中调用此方法
document.getElementById("help-button").addEventListener("click", () => {
  window.GitBook("navigateToAssistant");
});
```

### 聊天

#### `GitBook('postUserMessage', message)`

以用户输入的方式向聊天发送消息。

**参数：**

* `message` （字符串）：要发送到聊天的消息

**示例：**

```javascript
// 发送预设消息
window.GitBook("postUserMessage", "How do I reset my password?");

// 根据用户操作发送消息
function askAboutBilling() {
  window.GitBook("postUserMessage", "I have questions about my billing");
}

// 发送带有上下文的消息
const userPlan = "premium";
window.GitBook(
  "postUserMessage",
  `I'm on the ${userPlan} plan and need help with advanced features`
);
```

#### `GitBook('clearChat')`

清除当前聊天会话中的所有消息。

**示例：**

```javascript
// 清除聊天
window.GitBook("clearChat");

// 清除聊天并开始新的对话
function startNewConversation() {
  window.GitBook("clearChat");
  window.GitBook("postUserMessage", "Hello, I need help with a new issue");
}

// 切换上下文时清除聊天
document.getElementById("new-topic").addEventListener("click", () => {
  window.GitBook("clearChat");
  window.GitBook("navigateToAssistant");
});
```

### 配置

#### `GitBook('configure', settings)`

使用自定义选项配置嵌入内容。请参阅 [配置](https://gitbook.com/docs/documentation/zh/publish/embedding/implementation/script.md#configuration-options) 部分，了解可用选项。

**示例：**

```javascript
window.GitBook('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: ['什么是 GitBook？', '如何开始使用？']
});
```

## NPM 包 API

### 客户端工厂

#### `createGitBook(options)`

创建一个 GitBook 客户端实例。

**参数：**

* `options`: `{ siteURL: string }` - GitBook 文档站点的 URL

**返回：** `GitBookClient`

**示例：**

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

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

#### `client.getFrameURL(options)`

获取 iframe URL，并可选择启用经过身份验证的访问。

**参数：**

* `options`: `{ visitor?: { token?: string, unsignedClaims?: Record<string, unknown> }, colorScheme?: 'light' | 'dark' }` （可选）

**返回：** `string`

**示例：**

```javascript
const iframeURL = gitbook.getFrameURL({
  colorScheme: 'dark',
  visitor: {
    token: 'your-jwt-token',
    unsignedClaims: { userId: '123', plan: 'premium' }
  }
});
```

#### `client.createFrame(iframe)`

创建一个 frame 客户端，以便与 iframe 通信。

**参数：**

* `iframe`: `HTMLIFrameElement` - iframe 元素

**返回：** `GitBookFrameClient`

**示例：**

```javascript
const iframe = document.createElement('iframe');
iframe.src = gitbook.getFrameURL();
const frame = gitbook.createFrame(iframe);
```

### Frame 客户端方法

#### `frame.navigateToPage(path)`

在文档标签页中导航到指定页面。

**参数：**

* `path`: `string` - 页面的路径

#### `frame.navigateToAssistant()`

切换到助手标签页。

#### `frame.postUserMessage(message)`

向聊天发送消息。

**参数：**

* `message`: `string` - 要发送的消息

#### `frame.clearChat()`

清除聊天记录。

#### `frame.configure(settings)`

配置嵌入内容。可用选项请参阅 [配置](https://gitbook.com/docs/documentation/zh/publish/embedding/implementation/nodejs.md#configuration-options) 部分。

#### `frame.on(event, listener)`

注册事件监听器。

**参数：**

* `event`: `string` - 事件名称
* `listener`: `Function` - 回调函数

**返回值：** `() => void` - 取消订阅函数

**示例：**

```javascript
const unsubscribe = frame.on('close', () => {
  console.log('Frame closed');
});

// Later, unsubscribe
unsubscribe();
```

## React 组件 API

组件属性请参阅 [React 集成指南](https://gitbook.com/docs/documentation/zh/publish/embedding/implementation/react.md) ，useGitBook `useGitBook` 钩子 API 请参阅

`GitBookFrame` 支持 `assistantName`, `closeButton`, `colorScheme="light" | "dark"`以及用于经过身份验证的访问的 `visitor` 属性。

`useGitBook().getFrameURL()` 接受与 NPM 包相同的 `colorScheme` 参数。


---

# 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/configuration/reference.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.
