Skip to content

fix(chat): make code copy button work in non-secure contexts - #596

Open
yyyCode wants to merge 1 commit into
spring-ai-alibaba:mainfrom
yyyCode:fix/clipboard-copy-non-secure-context
Open

fix(chat): make code copy button work in non-secure contexts#596
yyyCode wants to merge 1 commit into
spring-ai-alibaba:mainfrom
yyyCode:fix/clipboard-copy-non-secure-context

Conversation

@yyyCode

@yyyCode yyyCode commented Jul 31, 2026

Copy link
Copy Markdown

Describe what this PR does / why we need it

修复问答流程中代码块「复制」按钮在非安全上下文(局域网 HTTP 访问)下无效的问题,解决 #350

根因:代码块复制按钮(markdown-plugin-highlight.ts 中的 window.copyCodeBlock)直接调用 navigator.clipboard.writeText。异步 Clipboard API 仅在安全上下文(HTTPS 或 localhost)下可用。当用户通过局域网 IP(如 http://192.168.x.x:port)以纯 HTTP 访问前端时,navigator.clipboardundefined,点击复制会在调用 .writeText 前就抛出 TypeError,连原有的 .catch 分支都进不去,按钮完全无反应 —— 即 issue 描述的「复制按钮无效」。

Does this pull request fix one issue?

Fixes #350

Describe how you did it

  • 新增工具函数 app/utils/clipboard.ts 中的 copyTextToClipboard(text)
    • 安全上下文优先使用异步 Clipboard API navigator.clipboard.writeText
    • 当 API 不可用(非安全上下文)或调用被拒绝时,降级到 document.execCommand('copy')(临时隐藏 textarea 方案),并在结束后清理该元素;
    • 统一返回 Promise<boolean> 表示是否复制成功。
  • app/utils/markdown/markdown-plugin-highlight.ts 改为调用该函数,依据返回结果切换按钮文案(已复制! / 复制失败),保持原有交互与提示不变。
  • 新增单元测试 app/utils/clipboard.test.ts,覆盖:安全上下文走 Clipboard API、writeText 失败后降级、非安全上下文降级成功、execCommand 失败返回 false、临时 textarea 复制后被移除。

Describe how to verify it

  1. 单元测试:cd data-agent-frontend-nuxt && pnpm test:unit(全部 22 条通过,含本次新增 5 条)。
  2. 构建:pnpm build 通过。
  3. 手动验证:通过局域网 IP 以 HTTP(非 localhost)访问前端,在问答结果的代码块上点击「复制」,粘贴可得到正确内容,按钮显示「已复制!」。

Special notes for reviews

  • 测试沿用仓库现有的默认 node 测试环境(其余测试也运行于此环境),通过 vi.stubGlobal 桩入最小 document/navigator/window,未引入 jsdom 等额外依赖。
  • 本次改动仅涉及前端,未改动后端与接口。

…ai-alibaba#350)

代码块的「复制」按钮此前直接调用 navigator.clipboard.writeText。该 API 仅在安全
上下文(HTTPS 或 localhost)可用,当通过局域网 IP 以 HTTP 访问时 navigator.clipboard
为 undefined,点击复制会直接抛出 TypeError,按钮无任何反应,即 issue 所述「复制按钮无效」。

新增 copyTextToClipboard 工具函数:优先使用异步 Clipboard API,在非安全上下文下降级到
document.execCommand('copy')(临时 textarea 方案),并统一返回成功与否。markdown 高亮插件
改为调用该函数,根据结果切换按钮文案。附带覆盖两条路径的单元测试。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] 问答流程的复制按钮无效

1 participant