Reputation: 1856
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
Reputation: 18524
There are multiple problems in your code
After eliminating these problems your code works as expected.
Sample demo of your use case
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"]
}
]
}
Ensured it respects all security changes
<html>
<head>
<script src="background.js"></script>
</head>
<body>
<textarea id="tmp-clipboard"></textarea>
</body>
</html>
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);
});
Passing content to be copied
chrome.extension.sendMessage({ text: "text you want to copy" });
Upvotes: 6