# API 参考

Docs Embed 根据你的集成方式提供不同的 API。本文档涵盖所有集成方式中可用的全部方法。

## 方法对比

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

## 独立脚本 API

### 初始化

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

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

**参数：**

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

**示例：**

```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` （string）：你想要导航到的页面路径

**示例：**

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

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

// 导航到 FAQ 部分
window.GitBook("navigateToPage", "/faq/billing");
```

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

直接导航到助手选项卡。

**示例：**

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

// 你可以在按钮点击时使用它
document.getElementById("help-button").addEventListener("click", () => {
  window.GitBook("navigateToAssistant");
});
```

### 聊天

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

像用户输入一样向聊天发送一条消息。

**参数：**

* `message` （string）：要发送到聊天的消息

**示例：**

```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)`

使用自定义选项配置嵌入。请参阅 [配置部分](/docs/documentation/zh/docs-site/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)`

导航到 docs 选项卡中的特定页面。

**参数：**

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

#### `frame.navigateToAssistant()`

切换到助手选项卡。

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

向聊天发送一条消息。

**参数：**

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

#### `frame.clearChat()`

清除聊天历史。

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

配置嵌入。请参阅 [配置部分](/docs/documentation/zh/docs-site/embedding/implementation/nodejs.md#configuration-options) 以了解可用选项。

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

注册事件监听器。

**参数：**

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

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

**示例：**

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

// 稍后取消订阅
unsubscribe();
```

## React 组件 API

请参阅 [React 集成指南](/docs/documentation/zh/docs-site/embedding/implementation/react.md) 以了解组件 props 以及 `useGitBook` hook API。

`GitBookFrame` 支持 `assistantName`, `closeButton`, `colorScheme="light" | "dark"`，以及 `visitor` 用于已验证访问的 prop。

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


---

# Agent Instructions: 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:

```
GET https://gitbook.com/docs/documentation/zh/docs-site/embedding/configuration/reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
