javascript - document.execCommand ('copy' ) 在 Chrome 上不工作

标签 javascript google-chrome clipboard

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

我找不到遇到同样问题的人,有很多类似的问题,但请不要将其标记为重复,除非它确实是重复的。

  • 我在 selection.addRange() 之前调用 selection.removeAllRanges()
  • selection.getRangeAt(0).cloneContents() 返回包含正确文本的片段
  • 文本区域中的文本未显示为选中
  • 如果我在 document.execCommand('copy') 之前调用 textarea.select(),文本将显示为选中状态并复制到剪贴板。我不想这样做,因为它会聚焦文本区域并导致页面滚动。
  • 在 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'));

最佳答案

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

似乎在 value 和文本区域的 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>

关于javascript - document.execCommand ('copy' ) 在 Chrome 上不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879184/

相关文章:

javascript - 更改 Javascript Infovis Toolkit/Force Directed Graph 中的节点形状

javascript - 我的 Rx-js groupJoin 有什么问题

android - 仅在 android Chrome 浏览器上出现在网站上的微弱线条

javascript - 全局变量 Chrome 扩展内容脚本

c# - 在 UserControl 上处理剪贴板副本

javascript - 将选定的文本复制到剪贴板而不使用 flash - 必须跨浏览器

delphi - 发送文本到其他应用程序

javascript - 我如何使用元素的 id 来触发 Meteor.js 中的事件

javascript - D3 将鼠标悬停在圆环图切片上时突出显示相应的表格条目

javascript - 令人困惑的 jQuery 行为