【问题标题】:Copy text to clipboard: Cannot read properties of undefined reading 'writeText'将文本复制到剪贴板:无法读取未定义读取“writeText”的属性
【发布时间】:2022-07-23 06:41:30
【问题描述】:

我有一个按钮

当我点击复制时

copyImageLinkText({ mouseenter, mouseleave }, e) {
  this.showCopiedText = !this.showCopiedText
  navigator.clipboard.writeText(this.imageLink)

  clearTimeout(this._timerId)
  mouseenter(e)
  this._timerId = setTimeout(() => mouseleave(e), 1000)
},

这条线似乎在我的 MacBook Pro 本地完美运行

navigator.clipboard.writeText(this.imageLink)

当我构建并将其部署到我的开发服务器时,它工作。

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component copy-paste


    【解决方案1】:

    使用navigator.clipboard 需要一个安全的来源。因此,如果您的开发环境是通过 HTTP 提供的,那么剪贴板方法将不可用。

    根据 MDN Clipboard 文档:“此功能仅在 secure contexts (HTTPS) 中可用”

    也许您可以检查此方法是否适用于 window.isSecureContext,并相应地禁用“复制文本”按钮。


    解决方法

    最好的选择是在您的开发环境中使用 HTTPS。

    但既然您要求解决方法,这里有一个(非常老套的)工作示例。它使用Document.exec 命令,该命令已被弃用,取而代之的是ClipboardAPI

    function unsecuredCopyToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand('copy');
      } catch (err) {
        console.error('Unable to copy to clipboard', err);
      }
      document.body.removeChild(textArea);
    }
    

    用法

    然后您可以使用navigator.clipboard == undefined 来使用回退方法,否则在支持的情况下使用普通的navigator.clipboard.writeText(...) 函数。 例如:

    const unsecuredCopyToClipboard=(text)=>{const textArea=document.createElement("textarea");textArea.value=text;document.body.appendChild(textArea);textArea.focus();textArea.select();try{document.execCommand('copy')}catch(err){console.error('Unable to copy to clipboard',err)}document.body.removeChild(textArea)};
    
    /**
     * Copies text, passed as param to clipboard
     * When clipboard API isn't available will use fallback
    */
    const copyToClipboard = (content) => {
      if (window.isSecureContext && navigator.clipboard) {
        navigator.clipboard.writeText(content);
      } else {
        unsecuredCopyToClipboard(content);
      }
    };
    <button onClick="buttonPress()">Copy msg to Clipboard</button>
    
    <script type="text/javascript"> const buttonPress = () => { copyToClipboard('Hello World!'); console.log('Clipboard updated ?\nNow try pasting!'); }; </script>

    【讨论】:

      【解决方案2】:

      最好使用async 并将您的代码放在try catch 块中。

      async copyCode() {
       try {
           await navigator.clipboard.writeText(this.input);
       } catch (e) {
           console.log(e);
       }
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-07
        • 2020-07-29
        • 1970-01-01
        • 2023-03-11
        • 2022-01-15
        • 2021-12-31
        • 2021-12-13
        相关资源
        最近更新 更多