Javascript 使用document.execCommand('copy')复制到剪贴板失败,文本较大

Javascript 使用document.execCommand('copy')复制到剪贴板失败,文本较大,javascript,dom,clipboard,Javascript,Dom,Clipboard,我正在使用隐藏的文本区域放置一些文本,选择它,然后使用document.execCommand将其复制到剪贴板。这通常有效,但如果文本较大,则返回false。在ChromeV55中,它似乎失败了大约180K个字符 以这种方式复制的数据量是否有限制?正常的Ctrl+C似乎不受相同的限制 注意:有人将此标记为的可能副本。这可能是一个类似的问题,但这个问题被标记为一个我不使用的特定框架,而且也没有得到回答。我相信我的问题更为笼统,而且仍然相关 我附上代码以供参考 function copy

我正在使用隐藏的文本区域放置一些文本,选择它,然后使用document.execCommand将其复制到剪贴板。这通常有效,但如果文本较大,则返回false。在ChromeV55中,它似乎失败了大约180K个字符

以这种方式复制的数据量是否有限制?正常的Ctrl+C似乎不受相同的限制

注意:有人将此标记为的可能副本。这可能是一个类似的问题,但这个问题被标记为一个我不使用的特定框架,而且也没有得到回答。我相信我的问题更为笼统,而且仍然相关

我附上代码以供参考

      function copyTextToClipboard(text) {
        var textArea = document.createElement('textarea');
        textArea.style.position = 'fixed';
        textArea.style.top = 0;
        textArea.style.left = 0;
        textArea.style.width = '2em';
        textArea.style.height = '2em';
        textArea.style.padding = 0;
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';
        textArea.style.background = 'transparent';
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
          var successful = document.execCommand('copy');
          var msg = successful ? 'successful' : 'unsuccessful';
          console.log('Copying text command was ' + msg);
        } catch (err) {
          console.log('Oops, unable to copy');
        }
        document.body.removeChild(textArea);
      }

问题更多地与呈现此长文本所需的时间有关,而不是与execCommand'copy'调用本身有关

Firefox引发了一条解释性很强的错误消息:

document.execCommand'cut'/'copy'被拒绝,因为它不是从短时间运行的用户生成的事件处理程序中调用的

您的代码生成文本花费的时间太长,因此浏览器无法将其识别为半可信事件

然后,解决方案是首先生成此文本,并且仅在聆听用户手势以调用execCommand之后生成。因此,为了使之成为可能,您可以(例如)侦听mousedown事件以生成文本,并且只有在mouseup事件中,您才能真正执行copy命令

常量文本='一些文本有点重复'+Date.now.repeat50000; 函数copyTextToClipboardtext{ //首先,我们创建textArea var textArea=document.createElement'textArea'; textArea.style.position='absolute'; textArea.style.opacity='0'; textArea.value=文本; document.body.appendChildtextArea; var execCopy=e=>{//在鼠标点击时触发 textArea.select; var successful=document.execCommand'copy'; var msg=successful?'successful':'successful'; log“复制文本命令为”+msg; document.body.removeChildtextArea; }; //这里是魔术 btn.addEventListener'mouseup',execCopy{ 一次:对 }; } //鼠标向下触发 btn.onmousedown=e=>copyTextToClipboardtext; 在剪贴板中复制一些文本
你的浏览器可能会有点麻烦,这是一个相当长的文本。。。请耐心等待

请参见编辑可能的副本。这个问题没有解决。