copyText.ts 1.02 KB
/**
 * 复制文本到剪贴板。优先 Clipboard API,非 HTTPS 等场景回退 execCommand。
 */
export async function copyText(text: unknown): Promise<void> {
    const value = String(text ?? "").trim();
    if (!value) {
        throw new Error("empty");
    }

    if (navigator.clipboard?.writeText) {
        try {
            await navigator.clipboard.writeText(value);
            return;
        } catch {
            // 非安全上下文或权限被拒时回退
        }
    }

    const textarea = document.createElement("textarea");
    textarea.value = value;
    textarea.setAttribute("readonly", "");
    textarea.style.position = "fixed";
    textarea.style.left = "-9999px";
    textarea.style.top = "0";
    textarea.style.opacity = "0";
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();
    textarea.setSelectionRange(0, value.length);

    const ok = document.execCommand("copy");
    document.body.removeChild(textarea);
    if (!ok) {
        throw new Error("copy failed");
    }
}