Chrome扩展-如何选择标签和复制的所有文本

Chrome extension - how to select all text of tab and copy

本文关键字:复制 标签 文本 选择 扩展 何选择 Chrome      更新时间:2023-09-26

谁能告诉我如何复制整个页面类似于按Ctrl+A,然后复制当前选项卡到剪贴板。

目前我有这个,但它什么也不做,虽然扩展已成功添加到chrome:

清单文件

"permissions":
[
   "clipboardRead",
   "clipboardWrite"
],
// etc
内容脚本

chrome.extension.sendRequest({ text: "text you want to copy" });

背景页

<html>
 <head>
 <script type="text/javascript">
   chrome.extension.onRequest.addListener(function (msg, sender, sendResponse) {
      var textarea = document.getElementById("tmp-clipboard");
      // now we put the message in the textarea
      textarea.value = msg.text;
      // and copy the text from the textarea
      textarea.select();
      document.execCommand("copy", false, null);

      // finally, cleanup / close the connection
      sendResponse({});
    });
  </script>
  </head>
  <body>
    <textarea id="tmp-clipboard"></textarea>
  </body>
</html>

弹出

<textarea id="tmp-clipboard"></textarea>
<input type="button" id="btn" value="Copy Page">

我不能让这个工作,不知道我在这里错过了什么。

有没有人可以指导如何模拟Ctrl+A然后是Ctrl+C当前选项卡,以便它存储在剪贴板中?

你的代码有多个问题

  • 从Chrome 20 sendRequest是不赞成sendMessage
  • 从Chrome 20的onRequest。addListener已被弃用,而支持onMessage.addListener
  • 由于CSP,你不能在你的代码中有标签

消除这些问题后,您的代码可以正常工作。

<标题> 示范

用例的示例演示

manifest.json

确保清单具有所有权限和注册

{
"name":"Copy Command",
"description":"http://stackoverflow.com/questions/14171654/chrome-extension-how-to-select-all-text-of-tab-and-copy",
"version":"1",
"manifest_version":2,
"background":{
    "page":"background.html"
},
"permissions":
[
   "clipboardRead",
   "clipboardWrite"
],
"content_scripts":[
{
"matches":["<all_urls>"],
"js":["script.js"]
}
]
}

background.html

确保遵守所有安全更改

<html>
<head>
<script src="background.js"></script>
</head>
<body>
<textarea id="tmp-clipboard"></textarea>
</body>
</html>

background.js

增加监听器模拟Ctrl + ACtrl + C

chrome.extension.onMessage.addListener(function (msg, sender, sendResponse) {
    //Set Content
    document.getElementById("tmp-clipboard").value = msg.text;
    //Get Input Element
    document.getElementById("tmp-clipboard").select();
    //Copy Content
    document.execCommand("Copy", false, null);
});

contentscript.js

传递要复制的内容

chrome.extension.sendMessage({ text: "text you want to copy" });
<标题>引用
  • manifest v2 changes
  • Chrome 20 Changes
  • 背景页