Chrome extension - how to select all tab text and copy

Can someone tell me how to copy the entire page, similar to pressing Ctrl + A, and then copy the current tab to the clipboard.

I currently have this, but it does nothing, although the extension has been successfully added to chrome:

manifest file

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

content script

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

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

pop-up window

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

I can’t get this to work, I wonder what I don’t see here.

Can someone please tell how to simulate Ctrl + A followed by Ctrl + C for the current tab so that it is stored in the clipboard?

+4
source share
1 answer

There are several problems in the code.

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

After resolving these issues, your code is working properly.

Demonstration

Demonstration example of your use case

manifest.json

Guaranteed 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

Enforcing All Security Changes

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

background.js

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

Transferring Content for Copy

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

References

+6
source

All Articles