north king
north king

Reputation: 113

Copy to clipboard in chrome extension V3

I am developing a chrome extension V3. I want to copy content to clipboard in my JS file.
The manifest.json as below,

    "background" :{
        "service_worker" :"eventPage.js"
    },
    "permissions" : [
        "contextMenus",
        "clipboardWrite"      
    ]

I have try 2 solution for copy feature.

Solution 1:

    const el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
  

The result:

Error in event handler: ReferenceError: document is not defined at copyToClipboard 

Solution 2:

navigator.clipboard.writeText(str);

The result:

Error in event handler: TypeError: Cannot read properties of undefined (reading 'writeText')

The chrome extension is run as a service worker. So it seems I can't access DOM document and have no grant of writeText. Does anyone have another suggestion?

Thanks.

Upvotes: 10

Views: 11100

Answers (2)

Nitz
Nitz

Reputation: 380

I'm not an expert in Chrome addons, but I believe that requesting <all_urls> is not best practice.
Instead, I got something to work by request activeTab instead, ditching the content scripts and injecting code to the active tab instead.
Manifest:

...
    "permissions": [
      "clipboardWrite"
      "activeTab",
      "scripting"
    ],
    "background": {
        "service_worker": "background.js"
    },
...

Background:

// To be injected to the active tab
function contentCopy(text) {
  navigator.clipboard.writeText(text);
}

async function copyLink(text, tab) {
  // Format as a whatsapp link
  const link = await getWhatsAppLink(text);
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: contentCopy,
    args: [link],
  });
}

So contentCopy is injected to the active tab and executed with the text I want to copy to clipboard.
Works well, and saves on problematic permissions (according to Google)

Upvotes: 6

relentless
relentless

Reputation: 503

I'll follow the excellent suggestion wOxxOm gave you, elaborating it in a concrete example. What you want to do is have a ContentScript.js that runs on any active tab with a web page, since you can't access the DOM from the backGround.js, and then send a message to this script, from where you would copy to the clipboard.

manifest.json

    "background" :{
        "service_worker" :"eventPage.js"
    },
    "permissions" : [
        "contextMenus",
        "clipboardWrite"      
    ],
   "content_scripts": [ // this is what you need to add
      {
         "matches": [
            "<all_urls>"
         ],
         "js": ["content.js"]
      }
   ],

From the background.js, you would send a message, that will be handled in the ContentScript.js

background.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, 
        {
            message: "copyText",
            textToCopy: "some text" 
        }, function(response) {})
})

In the contentScript.js, you would catch the message and copy it to the clipboard.

content.js

chrome.runtime.onMessage.addListener( // this is the message listener
    function(request, sender, sendResponse) {
        if (request.message === "copyText")
            copyToTheClipboard(request.textToCopy);
    }
);

async function copyToTheClipboard(textToCopy){
    const el = document.createElement('textarea');
    el.value = textToCopy;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
}

Upvotes: 18

Related Questions