Javascript 在 Chrome 扩展程序中复制到剪贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3436102/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy to Clipboard in Chrome Extension
提问by Kyle Ross
I'm making an extension for Google Chrome and I have hit a snag.
我正在为 Google Chrome 制作扩展程序,但遇到了障碍。
I need to copy a readonly textarea's content to the clipboard on click in the popup. Does anyone know the best way to go about this with pure Javascript and no Flash? I also have jQuery loaded in the extension, if that helps any. My current (non-working) code is...
我需要在弹出窗口中单击时将只读文本区域的内容复制到剪贴板。有没有人知道用纯 Javascript 和没有 Flash 来解决这个问题的最佳方法?我还在扩展中加载了 jQuery,如果有帮助的话。我当前的(非工作)代码是...
function copyHTMLCB() {
$('#lb_html').select();
$('#lb_html').focus();
textRange = document.lb_html_frm.lb_html.createTextRange();
textRange.execCommand("RemoveFormat");
textRange.execCommand("Copy");
alert("HTML has been copied to your clipboard."); }
采纳答案by serg
You can copy to clipboard using Experimental Clipboard API, but it is available only in the dev branch of a browser and not enabled by default (more info)..
您可以使用Experimental Clipboard API复制到剪贴板,但它仅在浏览器的 dev 分支中可用,并且默认情况下不启用(更多信息)。
回答by Jeff Gran
All credit goes to joelpt, but in case anyone else needs this to work in pure javascript without jQuery (I did), here's an adaptation of his solution:
所有功劳都归功于 joelpt,但如果其他人需要它在没有 jQuery 的纯 javascript 中工作(我做到了),这里是他的解决方案的改编版:
function copyTextToClipboard(text) {
  //Create a textbox field where we can insert text to. 
  var copyFrom = document.createElement("textarea");
  //Set the text content to be the text you wished to copy.
  copyFrom.textContent = text;
  //Append the textbox field into the body as a child. 
  //"execCommand()" only works when there exists selected text, and the text is inside 
  //document.body (meaning the text is part of a valid rendered HTML element).
  document.body.appendChild(copyFrom);
  //Select all the text!
  copyFrom.select();
  //Execute command
  document.execCommand('copy');
  //(Optional) De-select the text using blur(). 
  copyFrom.blur();
  //Remove the textbox field from the document.body, so no other JavaScript nor 
  //other elements can get access to this.
  document.body.removeChild(copyFrom);
}
回答by gjuggler
I found that the following works best, as it lets you specify the MIME type of the copied data:
我发现以下方法效果最好,因为它可以让您指定复制数据的 MIME 类型:
copy: function(str, mimeType) {
  document.oncopy = function(event) {
    event.clipboardData.setData(mimeType, str);
    event.preventDefault();
  };
  document.execCommand("copy", false, null);
}
回答by joelpt
I'm using this simple function to copy any given plaintext to the clipboard (Chrome only, uses jQuery):
我正在使用这个简单的函数将任何给定的纯文本复制到剪贴板(仅限 Chrome,使用 jQuery):
// Copy provided text to the clipboard.
function copyTextToClipboard(text) {
    var copyFrom = $('<textarea/>');
    copyFrom.text(text);
    $('body').append(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    copyFrom.remove();
}
// Usage example
copyTextToClipboard('This text will be copied to the clipboard.');
Due to the fast append-select-copy-remove sequence, it doesn't seem to be necessary to hide the textarea or give it any particular CSS/attributes. At least on my machine, Chrome doesn't even render it to screen before it's removed, even with very large chunks of text.
由于快速的追加-选择-复制-删除序列,似乎没有必要隐藏 textarea 或为其提供任何特定的 CSS/属性。至少在我的机器上,即使有非常大的文本块,Chrome 也不会在删除之前将其渲染到屏幕上。
Note that this will onlywork within a Chrome extension/app. If you're using a v2 manifest.json you should declare the 'clipboardWrite' permission there; this is mandatory for apps and recommended for extensions.
请注意,这仅适用于 Chrome 扩展程序/应用程序。如果你使用的是 v2 manifest.json,你应该在那里声明“clipboardWrite”权限;这对于应用程序是必需的,对于扩展程序是推荐的。
回答by atomicules
You can't copy a read only bit of text using execCommand("Copy"), it has to be an editable text area. The solution is to create a text input element and copy the text from there. Unfortunately you can't hide that element using display: noneor visibility: hiddenas that will also stop the select/copy command from working. However, you can 'hide' it using negative margins. Here's what I did in a Chrome Extension popup that obtains a short url. This is the bit of the code that re-writes the popup window with the shorturl (quick and dirty approach ;-)):
您不能使用 复制只读位文本execCommand("Copy"),它必须是可编辑的文本区域。解决方案是创建一个文本输入元素并从那里复制文本。不幸的是,您不能使用display: none或隐藏该元素,visibility: hidden因为这也会阻止选择/复制命令的工作。但是,您可以使用负边距“隐藏”它。这是我在 Chrome 扩展弹出窗口中所做的,该弹出窗口获取了一个短网址。这是使用shorturl重写弹出窗口的代码(快速而肮脏的方法;-)):
document.body.innerHTML = '<p><a href="'+shortlink+'" target="_blank" >'+shortlink+'</a><form style="margin-top: -35px; margin-left: -500px;"><input type="text" id="shortlink" value="'+shortlink+'"></form></p>'
document.getElementById("shortlink").select()
document.execCommand("Copy") 
回答by pinksy
I read somewhere that there are security restrictions with Javascript that stops you from interacting with the OS. I've had good success with ZeroClipboard in the past (http://code.google.com/p/zeroclipboard/), but it does use Flash. The Bitly website uses it quite effectively: http://bit.ly/
我在某处读到 Javascript 的安全限制会阻止您与操作系统交互。过去,我在 ZeroClipboard ( http://code.google.com/p/zeroclipboard/) 上取得了不错的成功,但它确实使用了 Flash。Bitly 网站非常有效地使用它:http://bit.ly/
回答by jakobinn
I had a similar problem where I had to copy text from an element using only javascript. I'll add the solution to that problem here for anyone interested. This solution works for many HTML elements, including textarea.
我有一个类似的问题,我不得不仅使用 javascript 从元素中复制文本。我会在这里为任何感兴趣的人添加该问题的解决方案。此解决方案适用于许多 HTML 元素,包括 textarea。
HTML:
HTML:
    <textarea id="text-to-copy">This is the text I want to copy</textarea>
    <span id="span-text-to-copy">This is the text I want to copy</span>
Javascript:
Javascript:
let textElement = document.getElementById("text-to-copy");
//remove selection of text before copying. We can also call this after copying
window.getSelection().removeAllRanges();
//create a Range object
let range = document.createRange();
//set the Range to contain a text node.
range.selectNode(textElement);
//Select the text node
window.getSelection().addRange(range);
try {
    //copy text
    document.execCommand('copy');
} catch(err) {
    console.log("Not able to copy ");
}
Note that if you wanted to copy a span element for instance, then you could get its text node and use it as a parameter for range.selectNode() to select that text:
请注意,例如,如果您想复制 span 元素,则可以获取其文本节点并将其用作 range.selectNode() 的参数来选择该文本:
let elementSpan = document.getElementById("span-text-to-copy");
let textNode = elementSpan.childNodes[0];
回答by Kartik Soneji
The Clipboard APIis now supported by Chrome, and is designed to replace document.execCommand.
该剪贴板API现在由Chrome浏览器的支持,旨在取代document.execCommand。
From MDN:
来自 MDN:
navigator.clipboard.writeText(text).then(() => {
    //clipboard successfully set
}, () => {
    //clipboard write failed, use fallback
});

