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?
Asked
Active
Viewed 4,260 times
1 Answers
7
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>
-
I have the text to be copied already in a text area in the popup. Do I still have to use a background page? I tried the doc.execCommand("copy", false, null); command but it doesn't seem to work. :S – thameera Mar 11 '11 at 11:16
-
This question/answer are very useful to beginners and this is a commonly asked question. Can this answer be updated to use `sendMessage` and `onMessage`? – Luke Jan 11 '15 at 18:47
-
How do you actually do Step 1, though? Wasn't that the OP's question? That's the part I've been trying to figure out: highlight some text on a page; click the custom Chrome extension's icon, and voila, highlighted text copied over to extension for further processing. Not sure how to grab from the DOM the text that the user has highlighted. I'm guessing if that part is figured out, you can send that text as a message. – ultrageek Nov 25 '21 at 13:05