document.execCommand('copy')无法在Chrome上运行

问题描述 投票:5回答:2

在Chrome上,只有document.execCommand('copy')返回true但不复制文本,它会清除剪贴板。

我找不到任何有同样问题的人,有很多类似的问题,但请不要将其标记为副本,除非它确实存在。

  • 我在selection.removeAllRanges()之前打电话给selection.addRange()
  • selection.getRangeAt(0).cloneContents()返回包含正确文本的片段
  • textarea中的文本未显示为已选中
  • 如果我在textarea.select()之前调用document.execCommand('copy'),则文本显示为已选中并且会被剪贴到剪贴板中。我不想这样做,因为它聚焦textarea并导致页面滚动。
  • 测试Chrome 61和63,MacOS
  • 在Safari中工作

这是我的代码(在单击事件监听器中使用) https://codepen.io/jakecr/pen/XVXvKz

var textarea = document.createElement('textarea');
textarea.textContent = 'coppied text';
document.body.appendChild(textarea);

var selection = document.getSelection();
var range = document.createRange();
range.selectNodeContents(textarea);
selection.removeAllRanges();
selection.addRange(range);

// DOESN'T WORK WITHOUT THIS
// textarea.select();

console.log(selection.getRangeAt(0).cloneContents());
console.log('copy success', document.execCommand('copy'));
javascript google-chrome clipboard
2个回答
16
投票

我不清楚这里到底发生了什么......

似乎在value和textarea的textContent属性之间应该使用什么不匹配。 Chrome似乎总是使用value,而Firefox则使用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);
}
<button id="btn">Copy!</button>
<textarea>You can paste here

</textarea>

由于chrome没有查看textContent属性,Range#selectNodeContents将不会在此浏览器上选择任何内容...

但是,您可以使用Range#selectNode,在这种情况下应返回相同的结果,并将解决此问题。

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);
  
})
<button id="btn">copy</button>
<textarea>You can paste here</textarea>

0
投票

我发现你不能动态插入输入字段,插入一些文本,然后将其复制到剪贴板。我能够从现有的输入标签中复制文本。

© www.soinside.com 2019 - 2024. All rights reserved.