Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy text to clipboard from a Google Chrome extension?

I found that there's an experimental clipboard class. But it works only in dev channel, right? Any idea how I can copy the text?

like image 478
thameera Avatar asked Mar 08 '11 17:03

thameera


People also ask

Can I copy text from a Chrome extension?

Click on Add to Chrome > Add Extension. Step 2: Open the website which has the protected text, click on the extension icon on the top right corner, and click on the Copyfish extension. Step 3: The extension provides you with a tool to select the area in which the text you want to copy is present.

How do I copy from chrome clipboard?

To copy text, highlight the section of text you want and use. Then hit Ctrl+C to copy and save it to the clipboard.


1 Answers

In your content script, have this:

// step 1: get the text you mean to copy
// (actual implementation not included)

// step 2: send it to your background page
chrome.extension.sendRequest({ text: "text you want to copy" });

In your background page, have this:

// step 3: set up your background page HTML
// and 
<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>
like image 102
Athena Avatar answered Sep 28 '22 04:09

Athena