> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/link-previews.md).

# 渲染链接和链接预览

将角色发送的链接转换为可点击链接、媒体卡片和 Open Graph 站点卡片，可在 Convai 小组件中或你自己的聊天界面中使用。

将角色发送的链接渲染为可点击链接，并显示图片、视频和文档卡片，而不是显示原样的 `[Doc](https://…)` Markdown。使用本页启用链接、通过 `linkPreviewResolver`添加 Open Graph 网站卡片，或在你自行构建的聊天界面中安全地渲染链接。

### 前提条件

* 已安装 Convai Web SDK，并且客户端可以连接。请参阅 [Web SDK 快速入门](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/quickstart.md).

{% hint style="warning" %}
链接功能取决于服务器端设置。 `preserveLinksInOutput` 是一个按会话设置的标志，由实时传输和 WebSocket 传输在 `/connect` 请求中发送，且服务器默认将其关闭。Convai 托管服务器会遵循此设置。未启用时，服务器会在文本到达客户端前移除每个 URL 的协议部分，因此指向 `https://docs.convai.com` 的 Markdown 链接会变成指向 `docs.convai.com`的链接，小组件会将其显示为带点状下划线的文本标签；而裸 URL 则会以纯文本形式显示，例如 `example.com/guide.pdf`。无论哪种情况都不会报错。
{% endhint %}

### 启用链接

在客户端配置中设置 `preserveLinksInOutput: true` 。 `ConvaiWidget` 和 `createConvaiWidget` 无需额外配置即可渲染链接。

{% tabs %}
{% tab title="React" %}
{% code title="src/App.tsx" %}

```tsx
import { useConvaiClient } from '@convai/web-sdk/react';
import { ConvaiWidget } from '@convai/web-widget/react';

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    preserveLinksInOutput: true,
  });

  return <ConvaiWidget convaiClient={client} />;
}
```

{% endcode %}
{% endtab %}

{% tab title="TypeScript" %}
{% code title="src/main.ts" %}

```typescript
import { ConvaiClient } from '@convai/web-sdk/core';
import { createConvaiWidget } from '@convai/web-widget/vanilla';

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  preserveLinksInOutput: true,
});

createConvaiWidget(document.body, { convaiClient: client });
```

{% endcode %}
{% endtab %}
{% endtabs %}

* 此标志只会在会话连接时读取一次。若要更改设置，请重新连接；不会触发重连的界面开关对当前会话无效。
* 该标志以 `preserve_links_in_output` 的形式发送；未设置时则省略该字段，因此会采用服务器默认设置。如果你在服务器上为 `/connect` 请求构造 `connectWithConnectionData()`，请在该请求中添加此字段。
* 如果你自行渲染 `chatMessages` ，请注意，启用此标志后，Markdown 链接会出现在 `content` 中。此设置不会影响语音；URL 永远不会被朗读出来。
* SSE 传输不会发送此标志，Interaction API 也没有等效的单请求设置：SSE 链接遵循部署的 `PRESERVE_LINKS_IN_LLM_OUTPUT` 设置，该设置默认关闭。在 SSE 客户端上设置 `preserveLinksInOutput` 不会产生任何效果。若要在 SSE 聊天中启用链接，请联系你的 Convai 对接人员，为你的部署开启该设置。

### 各类链接的渲染方式

两个小组件的链接渲染方式相同。预览仅显示在角色的消息气泡中。用户自己的消息气泡会保留可点击链接和相同的悬停标题，但不会嵌入媒体，因此粘贴的 URL 不会将远程媒体加载到聊天记录中。

| 链接                                                  | 角色的对话气泡                                       | 点击                                                     | 如果加载失败                                                                                  |
| --------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------- |
| 网页                                                  | 带下划线的链接。较长的裸 URL 会缩短显示；悬停可查看完整 URL。           | 新标签页                                                   | —                                                                                       |
| 图片（`png jpg gif webp avif`)                         | 卡片先显示加载骨架屏，然后显示图片和 `host · file` 说明文字。        | 会打开灯箱。按 Escape、点击背景或点击 **×** 即可关闭； **打开原图** 会在新标签页中打开。 | `Preview unavailable — host · file` 加载出错或 12 秒内未加载时显示。 `http:` 网页上的图片 `https:` 永远不会被请求。 |
| 视频（`mp4 webm mov ogg`)                              | 带原生控件的卡片。                                     | 播放、全屏                                                  | 与图片相同。                                                                                  |
| 文档（`pdf doc docx xls xlsx csv ppt pptx txt md zip`) | 文件卡片，带扩展名标识、文件名和 `host · Opens in a new tab`. | 新标签页                                                   | 不会获取任何内容，因此也不会发生失败。                                                                     |
| `mailto:`, `tel:`, `sms:`                           | 带图标和地址的标签。悬停可了解点击后会发生什么。                      | 交由操作系统处理                                               | 根据浏览器的设计，如果没有可用的处理程序，不会显示提示。                                                            |
| `ftp:`                                              | 带有 **FTP** 徽标的链接。悬停时会提示：大多数浏览器已不再打开这类链接。      | 新标签页                                                   | 浏览器会静默拒绝。                                                                               |
| `javascript:`, `data:` 及其他方案                        | 标签以点状文本显示，绝不会成为链接。                            | 无                                                      | —                                                                                       |

一条消息最多显示 6 张卡片。超出的媒体或文档链接会以普通链接形式呈现。

骨架屏是根据……生成的半透明色块 `currentColor`，因此它会与小组件所在的背景相匹配。在 `prefers-reduced-motion`.

#### 为原生 JavaScript 小组件设置卡片样式

`createConvaiWidget` 提供 `part` 属性，供你在宿主页面中设置样式：

| 元素   | 部件                                                                                                                                          |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| 链接   | `message-link`, `message-link-badge`, `message-link-blocked`, `message-contact`                                                             |
| 媒体卡片 | `message-media-card`, `message-media`, `message-media-zoom`, `message-media-skeleton`, `message-media-caption`, `message-media-unavailable` |
| 文档卡片 | `message-file-card`, `message-file-icon`, `message-file-name`, `message-file-meta`                                                          |
| 图片灯箱 | `lightbox`, `lightbox-backdrop`, `lightbox-image`, `lightbox-caption`, `lightbox-close`, `lightbox-open`                                    |
| 网站卡片 | `message-site-card`, `message-site-favicon`, `message-site-name`, `message-site-title`, `message-site-description`, `message-site-image`    |

### 为网页添加网站卡片

普通网页链接可以显示页面自身的卡片：网站图标、网站名称、标题、描述和图片，这些信息从页面的 Open Graph 和 Twitter 标签中读取。浏览器无法获取其他来源的页面，因此你需要提供一个解析器，让它向你的后端请求元数据。

{% tabs %}
{% tab title="React" %}
{% code title="src/App.tsx" %}

```tsx
import { useConvaiClient, type LinkPreviewResolver } from '@convai/web-sdk/react';
import { ConvaiWidget } from '@convai/web-widget/react';

const resolveLinkPreview: LinkPreviewResolver = async (url, signal) => {
  const res = await fetch(`/api/link-preview?url=${encodeURIComponent(url)}`, { signal });
  return res.status === 200 ? res.json() : null;
};

export default function App() {
  const client = useConvaiClient({
    apiKey: 'YOUR_API_KEY',
    characterId: 'YOUR_CHARACTER_ID',
    preserveLinksInOutput: true,
  });

  return <ConvaiWidget convaiClient={client} linkPreviewResolver={resolveLinkPreview} />;
}
```

{% endcode %}
{% endtab %}

{% tab title="TypeScript" %}
{% code title="src/main.ts" %}

```typescript
import { ConvaiClient } from '@convai/web-sdk/core';
import { type LinkPreviewResolver } from '@convai/web-sdk/vanilla';
import { createConvaiWidget } from '@convai/web-widget/vanilla';

const resolveLinkPreview: LinkPreviewResolver = async (url, signal) => {
  const res = await fetch(`/api/link-preview?url=${encodeURIComponent(url)}`, { signal });
  return res.status === 200 ? res.json() : null;
};

const client = new ConvaiClient({
  apiKey: 'YOUR_API_KEY',
  characterId: 'YOUR_CHARACTER_ID',
  preserveLinksInOutput: true,
});

createConvaiWidget(document.body, {
  convaiClient: client,
  linkPreviewResolver: resolveLinkPreview,
});
```

{% endcode %}
{% endtab %}
{% endtabs %}

`MarkdownRenderer` 接收与其 `resolveLinkPreview` 属性相同的函数。

* 解析器返回 `{ url, title?, description?, image?, siteName?, favicon? }` 或 `null`。只有当结果包含 `title` 或 `image`.
* 时才会显示卡片。解析器运行期间不会显示任何内容；如果解析失败或返回 `null`，也不会显示任何内容。链接本身不受影响。
* 每次页面加载期间都会按 URL 缓存结果，因此同一个 URL 即使出现两次，也只会发起一次请求。
* 网站卡片只会显示在角色的消息气泡中，并计入 6 张卡片的上限。媒体和文档链接会保留各自的卡片，不会展开预览。
* `image` 和 `favicon` 仅当它们是绝对 `http(s)` URL 时才会使用。所有其他字段都会作为文本渲染，而不会作为标记语言处理。

你的解析器端点会代表用户抓取网页。请要求用户提供会话，DNS 解析后拒绝私有地址和环回地址，对每次重定向重新检查，限制耗时和响应大小，并且绝不转发 Cookie。

### 在自己的聊天界面中渲染链接

如果你使用 `useConvaiClient` 或 `ConvaiClient` 建立连接，但自行绘制消息列表，那么角色的文本会以纯字符串的形式传给你。请使用 SDK 的气泡渲染器或其分词器来渲染。

#### 在 React 中使用气泡渲染器

`MarkdownRenderer` 是 React 小组件使用的组件，因此无需编写额外代码，就能获得卡片、骨架屏和协议白名单。向用户自己的消息气泡传入 `media={false}` 即可保留链接，同时移除嵌入内容。

{% code title="src/Bubble.tsx" %}

```tsx
import { MarkdownRenderer } from '@convai/web-widget/react';

export function Bubble({ text, isMe }: { text: string; isMe: boolean }) {
  return <MarkdownRenderer text={text} media={!isMe} />;
}
```

{% endcode %}

#### 基于分词器构建渲染器

`parseInlineMarkdown` 会将一行文本转换为节点，供你映射为自己的标记。它从以下模块导出： `@convai/web-sdk/core`, `@convai/web-sdk/vanilla` 和 `@convai/web-sdk/react`.

{% code title="src/render.ts" %}

```typescript
import { parseInlineMarkdown } from '@convai/web-sdk/core';

for (const node of parseInlineMarkdown(line)) {
  switch (node.kind) {
    case 'link':
      // node.media 是 'image' | 'video' | null：用于提示是否嵌入。
      renderAnchor(node.href, node.label, node.media);
      break;
    case 'image':
      renderImage(node.src, node.alt);
      break;
    case 'blocked':
      // 不安全的协议。将标签显示为纯文本，绝不能作为 href。
      renderPlainText(node.label);
      break;
    default:
      renderText(node);
  }
}
```

{% endcode %}

* 如果链接的结束 `)` 标记尚未流式传输到，链接会保持为文本，避免气泡在响应过程中不断切换形态而闪烁。
* `compactUrl` 会缩短显示用的长裸 URL，例如 `a.example.com/…/file.mp4`，但不会更改 href。绝不要将其结果用作 href。
* `linkKindForUrl` 和 `describeUrl` 会提供相同的分类结果以及 `host · file` 说明文字（组件使用的内容），而 `resolveLinkPreviewCached` 则会提供组件共用的解析器缓存，供你绘制自己的站点卡片时使用。

### 协议允许列表

只有 `http`, `https`, `ftp`, `ftps`, `mailto`, `tel` 和 `sms` 会成为链接。其他所有内容（包括 `javascript:` 和 `data:`）都会变成 `blocked` 节点，组件会将其呈现为文本。

{% hint style="warning" %}
绝不要将 `blocked` 节点的 `href` 放到锚点上。服务器不会清理协议：目标为 `javascript:alert(1)` 的 Markdown 链接会原样传到客户端，因此客户端是唯一的防护措施。如果你编写自己的分词器，而不是使用 `parseInlineMarkdown`，在渲染每个 href 之前，使用 `isSafeHref` 进行检查。
{% endhint %}

### API 参考

| 属性 / 方法                    | 类型                                                                                      | 说明                                                                                                                                    |
| -------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `preserveLinksInOutput`    | `boolean`                                                                               | 客户端选项。在 `/connect` 请求中以 `preserve_links_in_output`的形式发送。服务器默认关闭此选项。连接时读取一次。                                                           |
| `linkPreviewResolver`      | `LinkPreviewResolver`                                                                   | `ConvaiWidget` 属性和 `createConvaiWidget` 选项。用于普通网页链接的 Open Graph 查询；如不需要网站卡片，请省略此选项。                                                   |
| `MarkdownRenderer`         | `React.FC<{ text: string; media?: boolean; resolveLinkPreview?: LinkPreviewResolver }>` | React 小组件的气泡渲染器。 `media` 默认值为 `true`；对于用户自己的气泡，传入 `false` 。                                                                           |
| `resolveLinkPreview`       | `LinkPreviewResolver`                                                                   | `MarkdownRenderer` 属性，用于执行与 `linkPreviewResolver`.                                                                                    |
| `LinkPreviewResolver`      | `(url: string, signal: AbortSignal) => Promise<LinkPreviewMeta \| null>`                | 相同的查询。                                                                                                                                |
| `LinkPreviewMeta`          | `{ url, title?, description?, image?, siteName?, favicon? }`                            | 解析器返回的数据。                                                                                                                             |
| `resolveLinkPreviewCached` | `(resolver, url) => Promise<LinkPreviewMeta \| null>`                                   | 渲染器共享的按 URL 缓存。                                                                                                                       |
| `parseInlineMarkdown`      | `(line: string) => InlineNode[]`                                                        | 将一行文本转换为 `text`, `strong`, `em`, `link`, `image` 和 `blocked` 节点。                                                                      |
| `InlineNode`               | 联合类型                                                                                    | `{ kind: 'link', href, label, media }`, `{ kind: 'image', src, alt }`, `{ kind: 'blocked', href, label }`，以及 `text`, `strong` 和 `em`. |
| `isSafeHref`               | `(url: string) => boolean`                                                              | `true` 当 URL 的 scheme 在允许列表中，且可用作 href 时。                                                                                             |
| `mediaKindForUrl`          | `(url: string) => 'image' \| 'video' \| null`                                           | 根据文件扩展名对 URL 进行分类； `null` 表示无法预览。                                                                                                     |
| `linkKindForUrl`           | `(url: string) => LinkKind`                                                             | 安全 URL 的呈现类别： `web`, `image`, `video`, `document`, `email`, `phone`, `sms` 或 `ftp`.                                                   |
| `LinkKind`                 | 联合类型                                                                                    | linkKindForUrl `linkKindForUrl` 返回的值。                                                                                                 |
| `describeUrl`              | `(url: string) => string`                                                               | `host · file`，用于说明文字。                                                                                                                 |
| `compactUrl`               | `(url: string, max?: number) => string`                                                 | 仅用于显示的长 URL 缩短形式。                                                                                                                     |


---

# 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://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/link-previews.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.
