源码资源网 发表于 2024-8-2 14:50:32

复制内容显示navigator.clipboard undefined的问题与解决Cannot read properties of undefined (reading 'writeText')

复制内容显示navigator.clipboard undefined的问题与解决Cannot read properties of undefined (reading 'writeText')
分析问题
起因是测试提了个不管:点击单号复制小图标,会报脚本错误。
报错信息显示的就是 TypeError: Cannot read properties of undefined (reading ‘writeText’)
但是我自己在本地测试时,是没有问题的,在demo网站也没有问题。

在我要了测试的ip地址去测试,发现确实是会报错。
在查看相关代码发现问题在于,navigator对象下是否有clipboard对象。

在翻阅MDN文档后,发现问题所在。这个Navigator的clipboard属性是有限制的,必须是在支持的浏览器和安全上下文中可用。那么像我们的本地localhost,和我刚才的demo网站是用https的这些都属于安全上下文,所以测试并没有问题。在测试的机器里,因为是自己的ip域,并不是https。这个功能就会失效,所以就会报错undefined了


我们可以通过window.isSecureContext来判断是否是安全上下文。



如何解决1.代码兼容非安全域的写法。在安全域下使用 navigator.clipboard 提升效率,非安全域退回到 document.execCommand(‘copy’); 保证功能一直可用。
const handleCopy = (val) => {
    if (window.isSecureContext && navigator.clipboard) {
      navigator.clipboard
      .writeText(val)
      .then(() => {
          ElMessage({
            showClose: false,
            message: t('audit_center.other_source.success_copy'),
            type: 'success',
          });
      })
      .catch((err) => {
          ElMessage({
            showClose: false,
            message: `${t('audit_center.other_source.fail_copy')}:${err}`,
            type: 'error',
          });
      });
    } else {
      const copyElem = document.createElement('textarea');
      let styles = copyElem.style;
      styles.position = 'fixed';
      styles.zIndex = '0';
      styles.left = '-500px';
      styles.top = '-500px';
      copyElem.value = val;
      document.body.appendChild(copyElem);
      copyElem.focus();
      copyElem.select();
      let result = false;
      result = document.execCommand('copy');
      if (result) {
      ElMessage({
          showClose: false,
          message: t('audit_center.other_source.success_copy'),
          type: 'success',
      });
      copyElem.remove();
      } else {
      ElMessage({
          showClose: false,
          message: `${t('audit_center.other_source.fail_copy')}`,
          type: 'error',
      });
      }
    }
};


[*]引用第三方库
社区上有很多开源的复制剪切的jS库可以使用,第三方库考虑的比较全面,兼容问题都会处理好。https://github.com/soerenmartius/vue3-clipboardhttps://github.com/x-extends/xe-clipboard
PS:上面两个库如果无法下载,可以从本文附件中下载(两个都在附件中)--------------------------vue3-clipboard----------------------------------Installnpm install --save @soerenmartius/vue3-clipboardImport the v-clipboard directive globallysrc/main.tsimport { createApp } from 'vue'
import App from './App.vue'
import { VueClipboard } from '@soerenmartius/vue3-clipboard'

createApp(App).use(VueClipboard).mount('#app')
Apply the v-clipboard directive to an element<template>
<input v-model="value" />
<button v-clipboard="value">Copy</button>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
setup() {
    const value = ref('lorem')

    return { value }
},
})
</script>Copy value of an input, and handle events separately.<template>
<input v-model="value" />
<button
    v-clipboard:copy="value"
    v-clipboard:success="onSuccess"
    v-clipboard:error="onError"
>
    Copy
</button>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
setup() {
    const value = ref('lorem')

    const onSuccess = () => {
      console.log('success')
    }

    const onError = () => {
      console.log('error')
    }

    return { value, onSuccess, onError }
},
})
</script>Standalone usage of the toClipboard function<template>
<input v-model="value" />
<button @click="toClipboard(value)">Copy</button>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'

import { toClipboard } from '@soerenmartius/vue3-clipboard'

export default defineComponent({
setup() {
    const value = ref('lorem')

    return { value, toClipboard }
},
})
</script>本文示例:import { toClipboard } from '@soerenmartius/vue3-clipboard';

const handleCopy = (val) => {
    toClipboard(val)
      .then((res) => {
      ElMessage({
          showClose: false,
          message: t('audit_center.other_source.success_copy'),
          type: 'success',
      });
      })
      .catch((err) => {
      ElMessage({
          showClose: false,
          message: `${t('audit_center.other_source.fail_copy')}:${err}`,
          type: 'error',
      });
      });
};
---------------------------------xe-clipboard-----------------------------------Installingnpm install xe-clipboard<script src="https://cdn.jsdelivr.net/npm/xe-clipboard"></script>Example<button id="btn1">Copy</button>document.getElementById('btn1').addEventListener('click', function (evnt) {
// 由于浏览器的安全机制,操作剪贴板必须在事件之内才能有效
if (XEClipboard.copy('Copy this content to the clipboard.')) {
    alert('Copy success.')
} else {
    alert('The browser is not supported.')
}
})
static/image/hrline/1.gif
**** Hidden Message *****提取码下载:





页: [1]
查看完整版本: 复制内容显示navigator.clipboard undefined的问题与解决Cannot read properties of undefined (reading 'writeText')

免责声明:
1、本站提供的所有资源仅供参考学习使用,版权归原著所有,禁止下载本站资源参与商业和非法行为,请在24小时之内自行删除!
2、本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,请勿任何商业目的与商业用途。
3、若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。
4、论坛的所有内容都不保证其准确性,完整性,有效性,由于源码具有复制性,一经售出,概不退换。阅读本站内容因误导等因素而造成的损失本站不承担连带责任。
5、用户使用本网站必须遵守适用的法律法规,对于用户违法使用本站非法运营而引起的一切责任,由用户自行承担
6、本站所有资源来自互联网转载,版权归原著所有,用户访问和使用本站的条件是必须接受本站“免责声明”,如果不遵守,请勿访问或使用本网站
7、本站使用者因为违反本声明的规定而触犯中华人民共和国法律的,一切后果自己负责,本站不承担任何责任。
8、凡以任何方式登陆本网站或直接、间接使用本网站资料者,视为自愿接受本网站声明的约束。
9、本站以《2013 中华人民共和国计算机软件保护条例》第二章 “软件著作权” 第十七条为原则:为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。若有学员需要商用本站资源,请务必联系版权方购买正版授权!
10、本网站如无意中侵犯了某个企业或个人的知识产权,请来信【站长信箱312337667@qq.com】告之,本站将立即删除。
郑重声明:
本站所有资源仅供用户本地电脑学习源代码的内含设计思想和原理,禁止任何其他用途!
本站所有资源、教程来自互联网转载,仅供学习交流,不得商业运营资源,不确保资源完整性,图片和资源仅供参考,不提供任何技术服务。
本站资源仅供本地编辑研究学习参考,禁止未经资源商正版授权参与任何商业行为,违法行为!如需商业请购买各资源商正版授权
本站仅收集资源,提供用户自学研究使用,本站不存在私自接受协助用户架设游戏或资源,非法运营资源行为。