Skip to content

fix(h5): handle clipboard copy failures and clean up temporary textareas - #19548

Merged
Single-Dancer merged 6 commits into
NervJS:mainfrom
Jarvis636431:fix/h5-clipboard-copy-failure
Oct 23, 2026
Merged

Single-Dancer merged 6 commits into
NervJS:mainfrom
Jarvis636431:fix/h5-clipboard-copy-failure

Conversation

@Jarvis636431

@Jarvis636431 Jarvis636431 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

这个 PR 做了什么?

H5 setClipboardData currently reports success and displays the copy-success toast even when document.execCommand('copy') returns false. If selecting or copying throws, its temporary textarea remains attached to the document.

Check the command result and route failures through MethodHandler.fail. Remove the temporary textarea in finally, and move the explicit cache update after a successful copy. Preserve successful multiline copying and the hideDefaultMessage option.

Closes #19547

这个 PR 是什么类型?

  • 错误修复 (Bugfix)

这个 PR 涉及以下平台:

  • Web 端(H5)

验证

  • Added 8 Jest/jsdom regression cases for command failures, Promise rejection, callback behavior, DOM cleanup, selection exceptions, unavailable execCommand, cached content, and successful copies with/without the default toast. Six cases fail against the original implementation.
  • pnpm --filter @tarojs/taro-h5 test:ci --watchman=false: 26 suites, 187 tests passed.
  • ESLint passed for both changed files.
  • git -c core.whitespace=cr-at-eol diff --check passed; the source file retains its existing CRLF line endings.
  • pnpm --filter @tarojs/taro-h5 build: passed with exit code 0 outside the restricted execution sandbox; warnings remain in unchanged files.
  • Clipboard outcomes are simulated in jsdom; no separate real-browser/device clipboard compatibility matrix was run.

Summary by CodeRabbit

  • 问题修复
    • 修复 H5 端复制失败时仍将内容写入剪贴板缓存的问题;现在仅在复制成功后更新缓存。
    • 复制失败或缓存写入失败时会正确进入失败处理,避免误报成功。
    • 优化复制流程中的临时输入框清理,确保流程结束后及时移除。
    • 保持成功回调、完成回调及默认提示行为的一致性。

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 258abb27-1edc-4df7-b52b-2b9c83c66839
📥 Commits

Reviewing files that changed from the base of the PR and between d24853c and e07be5c.

📒 Files selected for processing: 2
  • packages/taro-h5/__tests__/device/clipboard.test.ts
  • packages/taro-h5/src/api/device/clipboard.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

H5 的 setClipboardData 现在会检查复制结果,在复制失败时通过失败流程处理,并始终清理临时 textarea。剪贴板缓存只在复制成功后更新。新增测试覆盖成功与失败路径。

Changes

H5 剪贴板复制

Layer / File(s) Summary
复制结果、清理与缓存更新
packages/taro-h5/src/api/device/clipboard.ts, packages/taro-h5/__tests__/device/clipboard.test.ts
复制命令返回 false 时,接口进入失败流程。无论复制是否成功,都会移除临时 textarea。复制成功后才更新缓存。测试覆盖异常、缓存保留、回调次数及默认提示行为。

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Low

Merge Risk: ⚪ Minimal · up to e07be

The tested copy-failure paths preserve the previous clipboard cache. No unresolved issue identified here prevents merging after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 标题准确概括了主要变更,包括处理 H5 剪贴板复制失败和清理临时 textarea。
Linked Issues check Passed PR 满足直接关联 issue [#19547] 的编码要求。clipboard.ts 检查 document.execCommand('copy') 的返回值,并在失败时调用 MethodHandler.fail。失败路径不调用成功回调且不显示成功提示。finally 使用 parentNode.removeChild 清理临时 textarea,并覆盖选择异常和接口不可…
Out of Scope Changes check Passed 变更范围符合 issue [#19547]。生产代码仅修改 H5 剪贴板复制失败处理、复制期间的缓存时机、临时 DOM 清理、缓存写入失败处理和成功提示行为。新增测试直接验证这些行为及成功路径。未发现与该 issue 无关的生产代码或测试变更。
Full details: Linked Issues check

Explanation

PR 满足直接关联 issue [#19547] 的编码要求。clipboard.ts 检查 document.execCommand('copy') 的返回值,并在失败时调用 MethodHandler.fail。失败路径不调用成功回调且不显示成功提示。finally 使用 parentNode.removeChild 清理临时 textarea,并覆盖选择异常和接口不可用场景。缓存写入发生在复制成功后;复制期间的 copy 事件不会提前写入缓存。测试覆盖返回 false、抛出异常、回调、缓存保留、DOM 清理、多行文本和 hideDefaultMessage。

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/taro-h5/__tests__/device/clipboard.test.ts

ESLint skipped: missing config or dependency (missing-dependency). The ESLint configuration references a package that is not available in the sandbox.

packages/taro-h5/src/api/device/clipboard.ts

ESLint skipped: the matched ESLint configuration already failed (missing-dependency).

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

我是小兔,检查复制结果
textarea 用完就离开
失败时,旧缓存仍安稳
成功时,新内容入缓存
耳朵轻摇,测试都跑完

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.56%. Comparing base (2ea942e) to head (e07be5c).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #19548      +/-   ##
==========================================
+ Coverage   56.43%   56.56%   +0.12%     
==========================================
  Files         467      467              
  Lines       25680    25686       +6     
  Branches     6452     6433      -19     
==========================================
+ Hits        14493    14529      +36     
+ Misses       9304     9169     -135     
- Partials     1883     1988     +105     
Flag Coverage Δ
taro-cli 60.27% <ø> (ø)
taro-runtime 58.78% <ø> (ø)
taro-web 65.06% <100.00%> (+0.81%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
packages/taro-h5/src/api/device/clipboard.ts 97.77% <100.00%> (+77.26%) ⬆️

... and 31 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Single-Dancer

Copy link
Copy Markdown
Collaborator

textarea.remove() 在较旧版本的 iOS Safari(iOS 9.3 及以下)中不支持,在这些环境中,即使 document.execCommand('copy') 已经执行成功,finally 中调用 textarea.remove() 仍可能抛出异常,导致 setClipboardData 返回失败,并且临时 textarea 无法被清理。

建议继续使用 document.body.removeChild(textarea),或者增加能力检测,在不支持 remove() 时回退到 removeChild。同时建议补充 textarea.remove 不可用时的测试。

另外,当前 setStorageSync 被移动到了系统剪贴板写入之后。如果 localStorage 因隐私模式、配额不足或被禁用而抛错,系统剪贴板实际上已经更新,但 API 会返回失败,getClipboardData 也可能继续返回旧缓存。建议明确这种部分失败场景的预期行为,并补充对应测试。

@Jarvis636431

Copy link
Copy Markdown
Contributor Author

@Single-Dancer 感谢指出这两个边界场景,已在 688575d 中跟进:

  • 清理改为在 finally 中检查父节点并调用 parentNode.removeChild(textarea),不再依赖 textarea.remove()。新增 3 个用例,覆盖 remove 不可用时复制成功、返回 false 和抛错,验证节点清理及原始复制错误不会被清理异常覆盖。这 3 个用例在修改前均失败,修改后通过。
  • 缓存部分保留写入异常时返回失败的语义,并在源码中说明系统剪贴板可能已更新。新增 4 个用例,模拟 QuotaExceededError 和 SecurityError,验证 Promise 拒绝或 fail/complete 各调用一次,不触发成功回调和 toast,临时节点被清理,仍可读取的旧缓存保持不变。

这里确实可能部分成功:系统复制与 localStorage 写入无法原子更新或回滚。本次没有吞掉存储异常,也没有将缓存写入移回复制前;若要改成系统复制成功即 API 成功,还需进一步约定缓存写入失败后的读取策略,避免随后读取旧缓存。

另外补充一点兼容性信息:核对 MDN Browser Compatibility Data 的 Element.remove 条目,Safari 支持起点为 7,safari_ios 为 mirror,因此“iOS 9.3 及以下不支持 remove()”这个版本范围不准确。不过,采用兼容性更广的 removeChild 清理仍然合理,已接受这一修改建议。以上为兼容性资料核查,未做旧版 iOS 真机验证。

验证:pnpm --filter @tarojs/taro-h5 test:ci --watchman=false,26 suites / 194 tests 全部通过;修改文件 ESLint 和保留原有 CRLF 行尾的 diff 检查均通过。新增场景使用 Jest/jsdom 模拟。

@Single-Dancer
Single-Dancer force-pushed the fix/h5-clipboard-copy-failure branch from 688575d to b279896 Compare October 22, 2026 10:18
@Single-Dancer

Copy link
Copy Markdown
Collaborator

还发现一个问题,execCommand('copy') 可能同步触发全局 copy 监听器,而监听器会在复制结果确认前更新 taro_clipboard。如果复制随后失败,系统剪贴板未更新,但 getClipboardData() 已经会读到新内容,造成缓存与真实剪贴板不一致。建议复制期间跳过监听器的缓存写入,统一由成功路径更新;同时注意 setStorageSync 的同步异常无法被后续 .catch() 捕获。

@Single-Dancer
Single-Dancer force-pushed the fix/h5-clipboard-copy-failure branch from b279896 to 3c56a55 Compare October 22, 2026 12:13
@Jarvis636431

Copy link
Copy Markdown
Contributor Author

@Single-Dancer 这个问题确实存在,已在 e07be5c 中修复并推送:

  • 增加程序复制期间的计数,在 finally 中恢复;全局 copy 监听器在此期间跳过缓存写入,统一由 execCommand('copy') 成功后的路径更新缓存。复制返回 false 或抛错时保留旧缓存,后续手动复制仍正常更新缓存。
  • 全局监听器改用 setStorageSync 配合同步 try/catch,避免存储同步异常逃逸;不再依赖捕获不到该异常的后续 .catch()。
  • 新增 5 个回归用例:模拟 execCommand 同步触发 copy 事件后成功、返回 false 或抛错,检查缓存写入时机、回调和节点清理,以及后续手动复制;另覆盖手动复制时的 QuotaExceededError 和 SecurityError。这 5 个用例在修复前均失败,修复后通过。

保留此前约定:系统复制成功后,如果显式缓存写入失败,API 仍返回失败。

验证:pnpm --filter @tarojs/taro-h5 test:ci --watchman=false,27 suites / 205 tests 全部通过;修改文件 ESLint 和保留原有 CRLF 行尾的 diff 检查均通过。上述事件与存储场景使用 Jest/jsdom 模拟,未做旧版 iOS 真机验证。

@Single-Dancer
Single-Dancer self-requested a review October 22, 2026 12:54
@Single-Dancer Single-Dancer added this to the 4.3.1 milestone Oct 22, 2026
@Single-Dancer
Single-Dancer merged commit de08853 into NervJS:main Oct 23, 2026
25 checks passed
@Jarvis636431
Jarvis636431 deleted the fix/h5-clipboard-copy-failure branch November 3, 2026 03:19
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.

[Bug]: H5 setClipboardData reports success when copying fails and leaks temporary textareas

2 participants