JS自动复制字符串到剪贴板

原理

自动复制到剪贴板可以分两步走:自动选中复制到剪贴板
<input>标签可以自动选中文本框内的文本,然后通过document.execCommand('copy')实现自动复制,或者,直接使用Navigator.clipboard操作剪贴板,可以写入和读取任意数据

  • document.execCommand是一个同步命令,在w3c中记为将要废弃的接口
  • Navigator.clipboard 使用Promise,是一个在草案阶段的剪贴板相关的接口

实现

任意文本自动复制-使用Input标签实现

function copyText(text) {
     let textarea = document.createElement("input");//创建input元素
     const currentFocus = document.activeElement;//当前获得焦点的元素,保存一下
     document.body.appendChild(textarea);//添加元素
     textarea.value = text;
     textarea.focus();
     
         textarea.setSelectionRange(0, textarea.value.length);//获取光标起始位置到结束位置
         //textarea.select(); 这个是直接选中所有的,效果和上面一样
     try {
         var flag = document.execCommand("copy");//执行复制
     } catch(eo) {
         var flag = false;
     }
     document.body.removeChild(textarea);//删除元素
     currentFocus.focus(); //恢复焦点
     return flag;
 }

任意元素内容自动复制-使用 Selection.addRange() +Navigator.clipboard实现

function copy(text)
{
  	navigator.clipboard.writeText(text).then(()=>{
  		alert("成功")
  	})
  	.catch(err=>
  	{
  		console.error("出错")
  	})
}

使用这个接口需要注意,这个接口尚未进入w3c标准,并且仅能在https协议页面内使用,详细可见Unblocking Clipboard Access

As with many new APIs, navigator.clipboard is only supported for pages served over HTTPS. To help prevent abuse, clipboard access is only allowed when a page is the active tab. Pages in active tabs can write to the clipboard without requesting permission, but reading from the clipboard always requires permission.

注意 ,Document.execCommand()这个方法被标记为不推荐的,未来可以使用Navigator.clipboard来实现剪贴功能

参考文档

  1. MDN Selection.addRange()
  2. MDN HTMLInputElement.setSelectionRange()
  3. js实现各种复制到剪贴板的方法
  4. MDN Document.execCommand()
  5. Google Clipboard文档
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章