关于js复制内容到浏览器原生剪贴板报错:Cannot read properties of undefined (reading ‘writeText‘)的解决方案【已全平台解决】


如果想直接看解决方案,请下滑到最后【完整代码】处

问题描述

开发「复制」功能

根据使用浏览器提供的原生功能 navigator.clipboard 返回的 Clipboard 对象的方法 writeText() 写文本到剪贴板。

在本地开发,或者说是在使用http://127.0.0.1:8088 或者 http://localhost:8088 本地调试时,是没有问题的,但是如果使用绑定 host 或者使用不安全域(域名+http)时,使用此功能,就会发生下面的报错:

Uncaught TypeError: Cannot read properties of undefined (reading 'writeText')

在这里插入图片描述


原因分析

安全问题

想必各位小伙伴或多或少会做过这样的操作,复制一下自己的个人信息然后粘贴到其他地方,看是所谓的方便如果遇到恶意有毒的钓鱼网站,那存在剪切板的信息就会一览无余,网络信息安全一直都是重中之重,所以在这方面上 navigator.clipboard 算是做足了防备。

SO~ 原因就是 浏览器禁用了非安全域的 navigator.clipboard 对象。

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


问题解决

所以要解决这个问题就是要做一个兼容的写法,当我们处于在安全域下使用 navigator.clipboard 提升效率,非安全域时退回到 document.execCommand('copy') 保证我们的复制功能一直可用。

document.execCommand

这里先说一下 document.execCommand

写过原生 Editor 编辑器大家应该都知道这个API吧,API 里面有很多方法,如:加粗/斜体/字号/字体颜色/插入图片/插入链接/复制/剪切/撤销… 具体可以看 MDN【但是这个API已经被官方废弃掉了】

👇「复制」功能示例:

function copy(text = ''){
	let input = document.createElement('input')
	input.style.position = 'fixed'
	input.style.top = '-10000px'
	input.style.zIndex = '-999'
	document.body.appendChild(input)
	input.value = text
	input.focus()
	input.select()
	try {
	  let result = document.execCommand('copy')
	  document.body.removeChild(input)
	  if (!result || result === 'unsuccessful') {
	    console.log('复制失败')
	  } else {
	    console.log('复制成功')
	  }
	} catch (e) {
	  document.body.removeChild(input)
	  alert('当前浏览器不支持复制功能,请检查更新或更换其他浏览器操作')
	}
}

完整代码

 function copyToClipboard(textToCopy) {
  	// navigator clipboard 需要https等安全上下文
    if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        return navigator.clipboard.writeText(textToCopy);
    } else {
     	// document.execCommand('copy') 向剪贴板写文本
        let input = document.createElement('input')
		input.style.position = 'fixed'
		input.style.top = '-10000px'
		input.style.zIndex = '-999'
		document.body.appendChild(input)
		input.value = textToCopy
		input.focus()
		input.select()
        try {
		  let result = document.execCommand('copy')
		  document.body.removeChild(input)
		  if (!result || result === 'unsuccessful') {
		    console.log('复制失败')
		  } else {
		    console.log('复制成功')
		  }
		} catch (e) {
		  document.body.removeChild(input)
		  alert('当前浏览器不支持复制功能,请检查更新或更换其他浏览器操作')
		}
    }
}

所有问题都解决啦~


总结

希望上面的内容对你的工作学习有所帮助!欢迎各位一键三连哦~

各位 加油!

Happy coding!

  • 19
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容报错信息是"TypeError: Cannot read properties of undefined (reading 'writeText')"。根据\[1\]中的描述,这个错误可能是由于导入方法不正确导致的。正确的导入方法应该是使用"import * as XLSX from 'xlsx'"而不是"import XLSX from 'xlsx'"。这是因为在node_modules\xlsx\types\index.d.ts中存放了xlsx的所有属性,需要用星号*表示导入所有属性(包括writeText)。所以请确保在导入xlsx时使用了正确的导入方法。 此外,根据\[3\]中的描述,如果在本地没有报错但在部署到测试环境时报错,可能是因为缺少一些文件或配置。请确保你的项目中包含了所需的文件,并且重启项目以确保所有更改生效。 希望这些信息对你有帮助!如果还有其他问题,请随时提问。 #### 引用[.reference_title] - *1* *2* [导入excel Uncaught TypeError: Cannot read properties of undefined (readingread‘)](https://blog.csdn.net/The_Lucky_one/article/details/127202499)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Uncaught TypeError: Cannot read properties of undefined (reading ‘meta‘)](https://blog.csdn.net/weixin_41414957/article/details/125501642)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值