在 Chrome 扩展程序中复制到剪贴板

新手上路,请多包涵

我正在为谷歌浏览器制作扩展程序,但遇到了麻烦。

我需要在弹出窗口中单击时将只读文本区域的内容复制到剪贴板。有谁知道使用纯 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."); }

原文由 Kyle Ross 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

您可以使用 Experimental Clipboard API 复制到剪贴板,但它仅在浏览器的开发分支中可用,默认情况下未启用( 更多信息)..

原文由 serg 发布,翻译遵循 CC BY-SA 3.0 许可协议

所有功劳都归功于 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);
}

原文由 Jeff Gran 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题