Files
Genarrative/src/services/clipboard.ts
kdletters b03c910f49 接入宿主壳原生剪贴板复制路径
H5 复制服务在 native_app 中优先调用 clipboard.writeText

保留浏览器 Clipboard API 与 legacy selection copy 回退路径

补充 HostBridge 剪贴板测试和宿主壳能力文档
2026-06-17 23:40:57 +08:00

60 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { writeHostClipboardText } from './host-bridge/hostBridge';
export async function copyTextToClipboard(value: string) {
const text = value.trim();
if (!text) {
return false;
}
if (await writeHostClipboardText({ text })) {
return true;
}
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// 部分内嵌浏览器会暴露 Clipboard API但会因权限上下文拒绝写入继续走兼容路径。
}
}
if (typeof document === 'undefined') {
return false;
}
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', 'true');
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
textarea.style.top = '0';
document.body.appendChild(textarea);
const selection = document.getSelection();
const selectedRange =
selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
textarea.focus();
textarea.select();
let copied = false;
try {
copied =
typeof document.execCommand === 'function' &&
document.execCommand('copy');
} catch {
copied = false;
} finally {
document.body.removeChild(textarea);
if (selection) {
selection.removeAllRanges();
if (selectedRange) {
selection.addRange(selectedRange);
}
}
}
return copied;
}