# 脚本标签

将 Docs Embed 添加到你的网站或应用中，最简单的方法是在 HTML 中引入一个独立脚本。每个 GitBook 文档站点都会提供一个可直接使用的嵌入脚本，它会自动加载该组件并将其连接到你的文档。本页将告诉你如何操作。

无需 SDK、构建步骤或框架集成。只需引入脚本，该组件就会显示在你的页面上。

## 开始使用

{% stepper %}
{% step %}

#### 复制你的嵌入脚本 URL

在 GitBook 应用中进入你的文档站点，导航到 **设置** 标签，然后进入 **AI 与 MCP** 并复制嵌入脚本 URL。

你也可以手动构建它：

```
https://YOUR_DOCS_DOMAIN/~gitbook/embed/script.js
```

将你的 `YOUR_DOCS_DOMAIN` 替换为你的真实文档站点域名。
{% endstep %}

{% step %}

#### 将脚本添加到你的 HTML

在你的页面 HTML 中添加以下标签。将其放在 `<head>` 或紧靠 `</body>`.

```html
<script src="https://YOUR_DOCS_DOMAIN/~gitbook/embed/script.js"></script>
<script>window.GitBook('show');</script>
```

{% endstep %}

{% step %}

#### 如果你的文档需要身份验证

如果你的文档 [受身份验证保护](/docs/documentation/zh/zhan-dian-fang-wen/authenticated-access.md)，则该脚本必须包含一个已签名的 JWT 令牌。

将其作为查询参数追加：

```html
<script src="https://YOUR_DOCS_DOMAIN/~gitbook/embed/script.js?jwt_token=YOUR_TOKEN"></script>
```

{% endstep %}

{% step %}

#### 验证

重新加载你的页面。

该组件应出现在右下角。
{% endstep %}
{% endstepper %}

### 可选地配置嵌入

你可以在显示该组件之前对其进行自定义。调用 `configure` 在脚本加载之后并且在调用 `window.GitBook('show')`.

```html
<script src="https://YOUR_DOCS_DOMAIN/~gitbook/embed/script.js"></script>
<script>
  window.GitBook('configure', {
    button: {
      label: '询问',
      icon: 'assistant' // assistant | sparkle | help | book
    },
    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？',
      '我该如何开始？'
    ]
  });

  window.GitBook('show');
</script>
```

使用此方法，你可以自定义：

* 按钮标签和图标
* 组件内可见的标签页
* 自定义操作按钮
* 问候标题和副标题
* 界面中显示的助手名称
* 助手内的关闭按钮
* 向用户显示的建议提示。

搜索默认启用。如果你设置 `tabs`，列出你想保留的每个标签页。

### 设置配色方案

默认情况下，嵌入内容会遵循 iframe 的 CSS `color-scheme`。这使它能够自动继承你的应用主题或浏览器偏好。

如果你想强制指定一种模式，请初始化嵌入并传递 `colorScheme` 在 `frameOptions`:

```html
<script src="https://YOUR_DOCS_DOMAIN/~gitbook/embed/script.js"></script>
<script>
  window.GitBook(
    'init',
    { siteURL: 'https://YOUR_DOCS_DOMAIN' },
    { colorScheme: 'dark' }
  );

  window.GitBook('show');
</script>
```

当你需要框架级选项时，请使用此模式，例如 `colorScheme` 或 `visitor`.

### 控制组件可见性

你可以在运行时通过 API 控制可见性和状态。

```html
<script>
  // 使组件可见
  window.GitBook('show');

  // 从页面中移除组件
  window.GitBook('hide');

  // 打开组件面板
  window.GitBook('open');

  // 关闭组件面板
  window.GitBook('close');

  // 切换打开或关闭状态
  window.GitBook('toggle');
</script>
```

当你想将该组件连接到你自己的 UI 触发器时，这非常有用。

### 以编程方式导航和交互

你可以通过代码驱动该组件来进行导航、切换标签页或发送消息。

```html
<script>
  // 在组件内打开特定文档页面
  window.GitBook('navigateToPage', '/getting-started');

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

  // 向助手发送一条用户消息
  window.GitBook('postUserMessage', '我该如何开始？');

  // 清除当前聊天记录
  window.GitBook('clearChat');
</script>
```

此功能的典型用途包括：

* 从你的应用中添加指向文档页面的深度链接
* 预填一个问题
* 在不同流程之间重置对话

### 动态加载嵌入脚本

如果你只想有条件地加载该组件，或者你需要在运行时附加身份验证令牌，请以编程方式注入脚本。

```html
<script>
  function loadGitBookEmbed() {
    var token = "" // 如果你的站点需要身份验证，请在此填入你的 JWT 令牌
    var script = document.createElement('script');
    script.src = 'https://YOUR_DOCS_DOMAIN/~gitbook/embed/script.js'
      + token ? '?jwt_token=' + encodeURIComponent(token) : ';
    script.async = true;
    script.onload = function () {
      window.GitBook('show');
    };
    document.head.appendChild(script);
  }

  loadGitBookEmbed();
</script>
```

当该组件应仅在用户操作后或根据功能标记加载时，请使用此模式

## API 参考

### 初始化

* `GitBook('init', options: { siteURL: string }, frameOptions?: { visitor?: {...}, colorScheme?: 'light' | 'dark' })` - 使用站点 URL 和可选框架选项初始化组件

### 组件控制

* `GitBook('show')` - 显示组件按钮
* `GitBook('hide')` - 隐藏组件按钮
* `GitBook('open')` - 打开组件窗口
* `GitBook('close')` - 关闭组件窗口
* `GitBook('toggle')` - 切换组件窗口

### 导航

* `GitBook('navigateToPage', path: string)` - 导航到文档标签页中的特定页面
* `GitBook('navigateToAssistant')` - 导航到助手标签页

### 聊天

* `GitBook('postUserMessage', message: string)` - 向聊天发送消息
* `GitBook('clearChat')` - 清除聊天历史

### 配置

* `GitBook('configure', settings: {...})` - 配置组件设置（见下方配置部分）
* `GitBook('unload')` - 将组件从页面中完全移除

## 配置选项

### `GitBook('configure')`

大多数配置选项都可通过 `GitBook('configure', {...})`:

#### `tabs`

覆盖要显示的标签页。

搜索默认启用。如果你设置 `tabs`，嵌入内容将只显示你列出的标签页。

* **输入**: `('assistant' | 'search' | 'docs')[]`
* **选项**:
  * `['assistant', 'search', 'docs']` - 显示所有标签页
  * `['search', 'docs']` - 仅显示搜索和文档
  * `['docs']` - 仅显示文档标签页

#### `actions`

在侧边栏中与标签页并排显示的自定义操作按钮。每个操作按钮在点击时都会触发回调。

**注意**：这之前被命名为 `buttons`。使用 `actions` 。

* **输入**: `Array<{ icon: string, label: string, onClick: () => void }>`
* **属性**:
  * `icon`: `string` - 图标名称。任何 [FontAwesome 图标](https://fontawesome.com/search) 都受支持
  * `标签`: `string` - 按钮标签文本
  * `onClick`: `() => void | Promise<void>` - 点击时的回调函数

#### `greeting`

显示在助手标签页中的欢迎消息。

* **输入**: `{ title: string, subtitle: string }`

#### `assistantName`

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

* **输入**: `string`
* **最大长度**: `32` 字符
* **示例**:

```javascript
window.GitBook('configure', {
  assistantName: '支持副驾'
});
```

#### `closeButton`

在助手内部显示关闭按钮。

* **输入**: `boolean`
* **示例**:

```javascript
window.GitBook('configure', {
  closeButton: true
});
```

#### `suggestions`

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

* **输入**: `string[]`

#### `trademark`

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

* **输入**: `boolean`
* **默认**: `true`
* **示例**:

```javascript
window.GitBook('configure', {
  trademark: false
});
```

#### `tools`

用于扩展助手的自定义 AI 工具。详见 [创建自定义工具](/docs/documentation/zh/docs-site/embedding/configuration/creating-custom-tools.md) 了解详情。

* **输入**: `Array<{ name: string, description: string, inputSchema: object, execute: Function, confirmation?: {...} }>`

#### `按钮`

配置用于启动嵌入的组件按钮（仅限独立脚本）。这使你可以自定义出现在页面右下角按钮的标签和图标。

* **输入**: `{ label: string, icon: 'assistant' | 'sparkle' | 'help' | 'book' }`
* **属性**:
  * `标签`: `string` - 按钮上显示的文本
  * `icon`: `'assistant' | 'sparkle' | 'help' | 'book'` - 按钮上显示的图标
    * `assistant` - <i class="fa-gitbook-assistant">:gitbook-assistant:</i> 助手图标
    * `sparkle` - <i class="fa-sparkle">:sparkle:</i> 闪光图标
    * `help` - <i class="fa-circle-question">:circle-question:</i> 帮助/问题图标
    * `book` - <i class="fa-book-open">:book-open:</i> 书本图标

**示例：**

```javascript
window.GitBook('configure', {
  button: {
    label: '询问',
    icon: 'assistant'
  }
});
```

{% hint style="info" %}
**注意：** 此选项仅在使用独立 script 标签实现时可用。对于 React 或 Node.js 实现，你需要创建自己的按钮来触发嵌入。
{% endhint %}

### `frameOptions`

某些选项是在框架上设置的，而不是作为配置项设置。在调用时传递它们 `frameOptions` 当调用 `GitBook('init', options, frameOptions)`.

#### `colorScheme`

覆盖嵌入的颜色方案。

如果省略，嵌入将遵循 iframe 的 CSS `color-scheme`，这使其能够继承父页面或浏览器偏好设置。

* **输入**: `'light' | 'dark'`
* **示例**:

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

#### `visitor` （已认证访问）

使用以下方式初始化时传递 `GitBook('init', options, frameOptions)`。用于 [自适应内容](/docs/documentation/zh/zhan-dian-fang-wen/adaptive-content.md) 并 [已认证访问](/docs/documentation/zh/zhan-dian-fang-wen/authenticated-access.md).

* **输入**: `{ token?: string, unsignedClaims?: Record<string, unknown> }`
* **属性**:
  * `token`: `string` （可选）- 已签名的 JWT 令牌
  * `unsignedClaims`: `Record<string, unknown>` （可选）- 用于动态表达式的未签名声明

## 常见陷阱

* **脚本 URL 不正确** – 请确保你使用的是实际的文档 URL，而不是示例 `docs.company.com`.
* **在脚本加载前调用 GitBook** – 将 API 调用包装在 `script.onload` 中，或将它们放在 script 标签之后。
* **无法访问需要身份验证的文档** – 如果你的文档需要登录，你必须提供 `visitor.token` 在初始化时。参见 [与受身份验证保护的文档配合使用](/docs/documentation/zh/docs-site/embedding/using-with-authenticated-docs.md).
* **CORS 或 CSP 错误** – 确保你站点的内容安全策略允许从你的 GitBook 域加载脚本和 iframe。
* **组件不可见** – 检查是否与页面上的其他元素存在 z-index 冲突。该组件默认使用较高的 z-index。
* **忘记初始化** – 确保调用 `GitBook('init', { siteURL: '...' })` 之后再使用其他方法。


---

# 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/implementation/script.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.
