Can someone explain how I can write to clipboard please? I've seen a lot of ways but I cant seem to understand how. Currently using manifest v3 and no background.js script.
popup.js (action: download) -> contentscript.js (see below)
function listener(info) {
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (!request.action) return sendResponse({
err: 'Error: No Request Action'
});
switch (request.action) {
case "copy":
var textCopy = info.links.join(', ').replace(/"/g, '') // Text to Copy (String)
navigator.clipboard.writeText(textCopy).then(() => {
sendResponse('success')
}, () => {
sendResponse('failed')
});
break;
// Other Requests
}
}
);
}
At least in manifest v2, this method works.
First you need to add the permission clipboardWrite to your manifest:
...
"permissions": ["clipboardWrite", ... ],
...
Then do something like what was answered here: https://stackoverflow.com/a/18455088
The idea is to create a temporary text area to put the text in which then allows you to select all the text inside with .select() and then copy it with document.execCommand('copy').
thanks to @cactus12 for the help here's the code that worked for me!
var textCopy = '' // Text to Copy
var copyFrom = document.createElement("textarea");
copyFrom.textContent = `${textCopy}`;
document.body.appendChild(copyFrom);
copyFrom.select();
document.execCommand(`copy`);
copyFrom.blur();
document.body.removeChild(copyFrom);