dev02
dev02

Reputation: 1856

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

Can anyone tell how to copy entire page similar to pressing Ctrl+A and then copying of current tab to clipboard.

Currently i have this but it is doing nothing though extension is successfully added to chrome:

manifest file

"permissions":
[
   "clipboardRead",
   "clipboardWrite"
],
// etc

content script

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

background page

<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>

popup

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

I cannot get this to work, wonder what I am missing here.

Can anyone please guide on how to mimic Ctrl+A followed by Ctrl+C for current tab so that it stores in clipboard ?

Upvotes: 4

Views: 6219

Answers (1)

Sudarshan
Sudarshan

Reputation: 18524

There are multiple problems in your code

  • From Chrome 20 sendRequest is deprecated in favor of sendMessage
  • From Chrome 20 onRequest.addListener is deprecated in favor of onMessage.addListener
  • Due to CSP you can not have tag in your code

After eliminating these problems your code works as expected.

Demonstration

Sample demo of your use case

manifest.json

Ensured manifest has all permissions and registrations

{
"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

Ensured it respects all security changes

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

background.js

Added Listener to Simulate Ctrl + A and Ctrl + 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

Passing content to be copied

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

References

Upvotes: 6

Related Questions