简体   繁体   English

document.execCommand('copy') 不适用于 Chrome

[英]document.execCommand('copy') not working on Chrome

On Chrome only document.execCommand('copy') returns true but does not copy the text, it clears the clipboard.在 Chrome 上,只有document.execCommand('copy')返回 true 但不复制文本,它会清除剪贴板。

I can't find anyone who's had the same problem, there are a lot of similar questions but please don't mark this as a duplicate unless it really is.我找不到任何有同样问题的人,有很多类似的问题,但请不要将其标记为重复,除非确实如此。

  • I am calling selection.removeAllRanges() before selection.addRange() .我在selection.removeAllRanges()之前调用selection.addRange()
  • selection.getRangeAt(0).cloneContents() returns a fragment containing the correct text selection.getRangeAt(0).cloneContents()返回包含正确文本的片段
  • The text in the textarea doesn't appear selected textarea 中的文本未显示为选中状态
  • If I call textarea.select() before document.execCommand('copy') the text appears selected and gets coppied to the clipboard.如果我在document.execCommand('copy') textarea.select()之前调用textarea.select()文本显示为选中状态并被复制到剪贴板。 I don't want to do this because it focuses the textarea and causes the page to scroll.我不想这样做,因为它聚焦 textarea 并导致页面滚动。
  • Tested on Chrome 61 and 63, MacOS在 Chrome 61 和 63、MacOS 上测试
  • Working in Safari在 Safari 中工作

Here's my code (used within a click event listener)这是我的代码(在单击事件侦听器中使用)
https://codepen.io/jakecr/pen/XVXvKz 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'));

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.似乎在 textarea 的valuetextContent属性之间应该使用什么不匹配。
Chrome seems to always use value , while Firefox uses 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>

Since chrome doesn't look at the textContent property, Range#selectNodeContents will select nothing on this browser...由于 chrome 不查看textContent属性,因此Range#selectNodeContents将在此浏览器上不选择任何内容...

However, you can use Range#selectNode which should return the same result in this case, and will workaround the issue.但是,您可以使用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>

For people reading this question in 2020, if you're having trouble with document.execCommand('copy') , you may want to try using the Clipboard API.对于在 2020 年阅读此问题的人,如果您在使用document.execCommand('copy')遇到问题,您可能想尝试使用剪贴板 API。

Per Mozilla :每个Mozilla

There are two ways browser extensions can interact with the system clipboard: the Document.execCommand() method and the modern asynchronous Clipboard API.浏览器扩展可以通过两种方式与系统剪贴板交互:Document.execCommand() 方法和现代异步剪贴板 API。

Also per Mozilla , document.execCommand() is now obsolete:同样根据Mozilladocument.execCommand()现在已过时:

This feature is obsolete.此功能已过时。 Although it may still work in some browsers, its use is discouraged since it could be removed at any time.尽管它可能在某些浏览器中仍然有效,但不鼓励使用它,因为它可以随时被删除。 Try to avoid using it.尽量避免使用它。

With the Clipboard API, writing text to the clipboard is particularly easy:使用剪贴板 API,将文本写入剪贴板特别容易:

const textToCopy = 'Hello there!'
navigator.clipboard.writeText(textToCopy)
  .then(() => { alert(`Copied!`) })
  .catch((error) => { alert(`Copy failed! ${error}`) })

More info:更多信息:

Mozilla's discussion of the two clipboard systems Mozilla 对两种剪贴板系统的讨论

Google's discussion of the two clipboard systems 谷歌对两种剪贴板系统的讨论

Another good discussion of the Clipboard API另一个关于剪贴板 API 的好讨论

CanIUse我可以用吗

I have found that you can't dynamically insert a input field, insert some text, and then copy it to the clipboard.我发现您无法动态插入输入字段,插入一些文本,然后将其复制到剪贴板。 I was able to copy text from an existing input tag.我能够从现有的输入标签复制文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 document.execCommand('copy') 命令在 Chrome 中不起作用 - document.execCommand('copy') Command not working in Chrome document.execCommand(&quot;copy&quot;) 不适用于所有浏览器 - document.execCommand("copy") not working on all browser Javascript document.execCommand“粗体”在Chrome中不起作用 - Javascript document.execCommand “bold” not working in chrome Chrome 中的 document.execCommand(&#39;heading&#39; ..&#39;) - document.execCommand('heading' ..') in Chrome 为什么document.execCommand(&#39;copy&#39;)在控制台中有效但在代码中无效 - Why document.execCommand('copy') working in console but not working in code 为什么document.execCommand(“ copy”)在Internet Explorer 11中不再起作用? - Why is document.execCommand(“copy”) no longer working in Internet Explorer 11? document.execCommand(&#39;copy&#39;) 不起作用,即使创建了 DOM 元素 - document.execCommand('copy') not working, even though the DOM element is created document.execCommand无法正常工作 - document.execCommand not working properly 为什么 document.execCommand("paste") 在 Google Chrome 中不起作用? - Why is document.execCommand("paste") not working in Google Chrome? document.execCommand(&#39;SaveAs&#39;,null,&#39;filename.csv&#39;)在chrome上不起作用 - document.execCommand('SaveAs',null,'filename.csv') is not working on chrome
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM