最近有个小需要,点击页面上的复制链接按钮,把以后页面的地址复制到剪贴板,不便粘贴到其余中央分享。
是否有现成的库?
当然有了,比方clipboardjs,体积小,而且能够灵便的引入到我的项目中。
不过,如果你和我一样对这个性能的实现很好奇,能够接着向下看,其实也很简略。
JS复制内容到剪贴板的实现
如果在百度中这样搜寻,失去的答案大部分都是教你应用上面这个办法:
document.execCommand('copy')
不过如果去查阅一下比拟权威的文档如 MDN、Stack Overflow,就会发现下面的办法曾经被废除了,曾经不举荐应用,因为不能确定哪一天就真的用不了了。
所以应该找一种稳当的形式实现这个性能,Stack Overflow 上有这样一个答复集体认为比拟不错,贴下代码:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body><button onclick="copyTextToClipboard(window.location.href)">复制链接</button><script> function fallbackCopyTextToClipboard() { // 1.创立一个可选中元素 let textArea = document.createElement("textarea"); textArea.value = window.location.href; // 2.应用定位,阻止页面滚动 textArea.style.top = "0"; textArea.style.left = "0"; textArea.style.position = "fixed"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Fallback: Copying text command was ' + msg); } catch (err) { console.error('Fallback: Oops, unable to copy', err); } // 3.移除元素 document.body.removeChild(textArea); } function copyTextToClipboard(text) { if (!navigator.clipboard) { fallbackCopyTextToClipboard(text); return; } navigator.clipboard.writeText(text).then(function() { console.log('Async: Copying to clipboard was successful!'); }, function(err) { console.error('Async: Could not copy text: ', err); }); }</script></body></html>
咱们能够把下面的办法称为 Async + Fallback (即优先应用navigator.clipboard,如果这种比拟新的形式没有被你的浏览器反对,就应用document.execCommand 这个行将被废除的形式)
原理剖析
实质上document.execCommand是在你的页面中创立了一个没有用的DOM元素,如textArea、input,它们的特点是内容能够被选中,而后被document.execCommand操纵,进而复制内容到剪贴板。这种形式看起来并不优雅,所以咱们优先举荐navigator.clipboard.writeText(text).then()。如果用户的浏览器还没有反对navigator.clipboard,再将document.execCommand作为候选,这样兼容性比拟好。
文章首发于 IICOOM-集体博客 《JavaScript复制内容到剪贴板》