document.execCommand('copy') not working on Chrome

前端 未结 3 1181
遇见更好的自我
遇见更好的自我 2021-02-19 17:10

On Chrome only document.execCommand(\'copy\') returns true but does not copy the text, it clears the clipboard.

I can\'t find anyone who\'s had the same pro

3条回答
  •  名媛妹妹
    2021-02-19 17:43

    I am not really clear as to what really happens here...

    It seems there is a mismatch as to what should be used between the value and the textContent properties of your textarea.
    Chrome seems to always use value, while Firefox uses textContent.

    btn.onclick = e => {
      const txt = document.createElement('textarea');
      document.body.appendChild(txt);
      txt.value = 'from value'; // chrome uses this
      txt.textContent = 'from textContent'; // FF uses this
      var sel = getSelection();
      var range = document.createRange();
      range.selectNode(txt);
      sel.removeAllRanges();
      sel.addRange(range);
      if(document.execCommand('copy')){
        console.log('copied');
      }
      document.body.removeChild(txt);
    }
    
    

    Since chrome doesn't look at the textContent property, Range#selectNodeContents will select nothing on this browser...

    However, you can use Range#selectNode which should return the same result in this case, and will workaround the issue.

    document.getElementById('btn').addEventListener('click', function(){
      var textarea = document.createElement('textarea');
      textarea.textContent = 'copied text';
      document.body.appendChild(textarea);
    
      var selection = document.getSelection();
      var range = document.createRange();
    //  range.selectNodeContents(textarea);
      range.selectNode(textarea);
      selection.removeAllRanges();
      selection.addRange(range);
    
      console.log('copy success', document.execCommand('copy'));
      selection.removeAllRanges();
    
      document.body.removeChild(textarea);
      
    })
    
    

提交回复
热议问题