Copying to clipboard with document.execCommand('copy') fails with big texts

前端 未结 1 660
南旧
南旧 2020-12-29 12:30

I\'m using a hidden text area to put some text, select it and then using document.execCommand to copy it to the clipboard. This usually works but fails (returns false) when

相关标签:
1条回答
  • 2020-12-29 12:50

    The problem has more to do with the time it takes to render this long text than the execCommand('copy') call itself.

    Firefox raises an quite explanatory error message :

    document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.

    Your code takes too long to generate the text, and thus the browser doesn't recognizes it as an semi-trusted event...

    The solution is then to generate this text first, and only after listen to an user-gesture to call execCommand. So to make it possible, you can e.g. listen to a mousedown event to generate the text, and only in the mouseup event will you really execute the copy command.

    const text = ('some text a bit repetitive ' + Date.now()).repeat(50000);
    
    function copyTextToClipboard(text) {
      // first we create the textArea
      var textArea = document.createElement('textarea');
      textArea.style.position = 'absolute';
      textArea.style.opacity = '0';
      textArea.value = text;
      document.body.appendChild(textArea);
    
      var execCopy = e => {   // triggered on mouseup
        textArea.select();
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
        document.body.removeChild(textArea);
      };
      // here the magic
      btn.addEventListener('mouseup', execCopy, {
        once: true 
      });
    }
    // triggered on mousedown
    btn.onmousedown = e => copyTextToClipboard(text);
    <button id="btn">copy some text in your clipboard</button>
    <p>May struggle your browser a little bit, it's quite a long text... Please be patient</p>

    0 讨论(0)
提交回复
热议问题