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

# 脚本标签

了解如何使用单个 script 标签将 Docs Embed 小组件添加到任意网站或 Web 应用

将 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 %}

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

如果你的文档 [需要通过身份验证才能访问](https://gitbook.com/docs/documentation/zh/publish/site-audience/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' // 助手 | 闪光 | 帮助 | 书籍
    },
    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>
```

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

* 按钮标签和图标
* 小组件内显示的选项卡
* 自定义操作按钮
* 欢迎标题和副标题
* UI 中显示的助手名称
* 助手内的关闭按钮
* 向用户显示的建议提示词。

搜索默认处于启用状态。如果设置了 `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` - 图标名称。支持所有 [Font Awesome 图标](https://fontawesome.com/search) 。
  * `label`: `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`

用于扩展 Assistant 的自定义 AI 工具。详情请参阅 [创建自定义工具](https://gitbook.com/docs/documentation/zh/publish/embedding/configuration/creating-custom-tools.md) 。

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

#### `button`

配置用于启动嵌入内容的小组件按钮（仅限独立脚本）。这使您可以自定义页面右下角显示的按钮的标签和图标。

* **类型**: `{ label: string, icon: 'assistant' | 'sparkle' | 'help' | 'book' }`
* **属性**:
  * `label`: `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" %}
**注意：** 此选项仅适用于独立脚本标签的实现方式。对于 React 或 Node.js 实现，你需要自行创建按钮来触发嵌入内容。
{% endhint %}

### `frameOptions`

某些选项会设置在 frame 上，而不是作为配置项设置。调用时将它们传入 `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)`。用于 [自适应内容](https://gitbook.com/docs/documentation/zh/publish/adaptive-content.md) 和 [身份验证访问](https://gitbook.com/docs/documentation/zh/publish/site-audience/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` 。请参阅 [与需要身份验证的文档配合使用](https://gitbook.com/docs/documentation/zh/publish/embedding/using-with-authenticated-docs.md).
* **CORS 或 CSP 错误** – 请确保网站的内容安全策略允许从 GitBook 域加载脚本和 iframe。
* **小组件不可见** – 检查页面上的其他元素是否存在 z-index 冲突。小组件默认使用较高的 z-index。
* **忘记初始化** – 请确保在使用其他方法之前调用 `GitBook('init', { siteURL: '...' })` 。


---

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