7

As reference here in order to read Clipboard text in a chrome extension, you have to:

  • request "clipboardRead" permission in your manifest
  • create a background script, since only the background script can access the clipboard
  • create an element in your background page to accept the clipboard paste action. If you make this a textarea, you will get plain-text, if you make it a div with contentEditable=true, you will get Formatted HTML
  • if you want to pass the clipboard data back to an in page script, you'll need to use the message-passing API

But this only works in manifest_version 2, because in manifest_version 3 you can not have a background script, but a service worker.

In this service worker you can not have normal functions, so I have a

chrome.runtime.onMessage.addListener

in this "manifest_version 3 service worker background.js script", and I invoke a message from my popup.html for example.

But then, the problem is that this service worker has no "document", so I can not create the textarea to do the trick of copying the contents there and call document.execCommand.

So ... is there any way to copy contents to clipBoard in Manifest Version 3 ?

FlamingMoe
  • 2,709
  • 5
  • 39
  • 64
  • 1
    You'll have to do it in the active tab by creating an [extension iframe](https://stackoverflow.com/a/25100953) or opening a new extension tab/window. – wOxxOm Jun 23 '21 at 02:34
  • opening a new tab for just copying in the clipboard ? that's not very friendly for user experience ;-) creating a iframe has the same problem... "copy command just work in a background script" – FlamingMoe Jun 23 '21 at 07:26
  • 2
    The iframe won't be visible. BTW it's reported in https://crbug.com/1160302. – wOxxOm Jun 23 '21 at 09:47

1 Answers1

1

Here is a pretty crude (but working) solution:

  1. In your background script, set up some sort of listener to trigger the copy function.
  2. Set up an injection script/function that creates an invisible textarea with the desired text to be copied. In the same script/function, add copying to clipboard ala the solution here.
  3. In your background.js script, set up the code to retrieve the current active tab (as @wOxxOm suggests) and use the tab id to dynamically execute your injection script/function.

Since your injected script (aka content script) can access a document, this time the document being the document of the open web page, you can create an invisible textarea, set the textarea to have the text you want to copy, and then use document.execCommand("copy"); to copy the text onto the clipboard.

Here is an example of my background.js script which copies text onto your clipboard when you press Ctrl+Shift+K.

Dharman
  • 30,962
  • 25
  • 85
  • 135
ricoknowsjs
  • 33
  • 1
  • 6