0

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
               
            }

        }
    );
}
SamJones
  • 71
  • 4
  • And what is the problem with your code? Which API do you use to send the message? Note that the popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu. – wOxxOm Feb 06 '22 at 15:10
  • it doesnt copy to clipboard, using `chrome.tabs.sendMessage` to send messages to the content script, would that effect the content scripts ability to copy to clipboard? – SamJones Feb 06 '22 at 20:11
  • The clipboard is just one per the entire system so you can write to it in your popup.js. – wOxxOm Feb 06 '22 at 20:18

2 Answers2

1

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);
SamJones
  • 71
  • 4
0

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').

cactus12
  • 56
  • 1
  • 1
  • 9