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文档
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值