实现一个复制粘贴✌️

1,365 阅读1分钟

每天记录📝点 总会有收获~

今天在做一个PC端复制粘贴的功能,本来想使用document.execCommand来实现,结果发现:

  • document.execCommand对于有些浏览器环境不兼容,得自己来兼容。
  • document.execCommand MDN上已经废弃了,改用navigator.clipboard了。

基于上面第一点👆打算用别人封装📦好的库,找了一圈像clipboard 、copy-to-clipboard、react-copy-to-clipboard都是基于document.execCommand来实现的,遂作罢。

于是,自己开始用navigator.clipboard来写,但是!只有在用户事先授予网站或应用对剪切板的访问许可之后,才能使用异步剪切板读写方法。 否则,会报错:

Uncaught (in promise) TypeError: Cannot read property 'writeText' of undefined at HTMLInputElement.<anonymous>

这是因为浏览器禁用了非安全域的 navigator.clipboard 对象,只有以下地址是安全的。

安全域包括本地访问与开启TLS安全认证的地址,如 https 协议的地址、127.0.0.1 或 localhost 。

一开始想的是使用:

在安全域下使用 navigator.clipboard 提升效率,非安全域退回到用document.execCommand('copy');库,保证功能可用。

function copyToClipboard(textToCopy) { 
    // navigator clipboard 需要https等安全上下文 
    if (navigator.clipboard && window.isSecureContext) { 
        // navigator clipboard 向剪贴板写文本 
        return navigator.clipboard.writeText(textToCopy); 
    } else { // 创建text area 
        let textArea = document.createElement("textarea"); 
        textArea.value = textToCopy; 
        // 使text area不在viewport,同时设置不可见 
        textArea.style.position = "absolute"; 
        textArea.style.opacity = 0; 
        textArea.style.left = "-999999px"; 
        textArea.style.top = "-999999px"; document.body.appendChild(textArea); 
        textArea.focus(); 
        textArea.select(); 
        return new Promise((res, rej) => { 
        // 执行复制命令并移除文本框 
            document.execCommand('copy') ? res() : rej(); 
            textArea.remove(); 
        }); 
    } 
}

后来想到document.execCommand的兼容性,所以采用了引入copy-to-clipboard库的方式

 if (navigator && navigator.clipboard && window.isSecureContext) {
    navigator.clipboard
        .writeText(url)
        .then(() => {
            alert('复制成功');
        })
        .catch(() => {
            alert('复制失败');
        });
} else {
    if (copy(url)) {
        alert('复制成功');
    } else {
        alert('复制失败');
    }
}

后续有空可以看看clipboard库,flag又来了🐒

相关连接🔗:阮一峰-clipboard