Skip to content

浏览器js复制文本到剪贴板

js
export async function copyText(text) {
    try {
        // 优先使用 Clipboard API(HTTPS/localhost 环境)
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(text);
        } else {
            // 回退方案:使用 document.execCommand(兼容 HTTP 内网环境)
            fallbackCopyTextToClipboard(text);
        }
        console.log('复制成功')
    } catch (err) {
        console.error('复制失败:', err);
    }
}

// 回退方案:兼容 HTTP 内网环境
function fallbackCopyTextToClipboard(text) {
    try {
        const textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.style.position = "fixed"; // 避免影响页面布局
        textArea.style.top = "0";
        textArea.style.left = "0";
        textArea.style.width = "2em";
        textArea.style.height = "2em";
        textArea.style.padding = "0";
        textArea.style.border = "none";
        textArea.style.outline = "none";
        textArea.style.boxShadow = "none";
        textArea.style.background = "transparent";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        document.execCommand('copy');
    } catch (err) {
        console.error('复制失败(回退方案):', err);
        throw err
    } finally {
        document.body.removeChild(textArea);
    }
}
/src/technology/dateblog/2025/06/20250616-%E6%B5%8F%E8%A7%88%E5%99%A8js%E5%A4%8D%E5%88%B6%E6%96%87%E6%9C%AC%E5%88%B0%E5%89%AA%E8%B4%B4%E6%9D%BF.html