ddreian
ddreian

Reputation: 1856

How can I use navigator.clipboard.readText() in a Chrome extension?

I wrote a Firefox extension that reads the clipboard and if it has some PEM certificate, it will print it's details in a new tab. I'm trying to port to Chrome. It does not work. What am I doing wrong?

I asked for the clipboardRead in manifest.json and I run this in background script and it works fine in Firefox.

 navigator.clipboard.readText().then(function (textFromClipboard) {
   //do stuff with textFromClipboard
 });

This fails in Chrome with "Failed to execute 'readText' on 'Clipboard': Illegal invocation". What am I doing wrong? How can I make this work in Chrome also? Most answers involve creating an input, getting focus, executing paste. That is really complicated, I hope I don't have to do this. It works really well in Firefox, why is it complicated in Chrome?

Upvotes: 3

Views: 16933

Answers (2)

Морфей
Морфей

Reputation: 90

add In your code (popup.js):

navigator.clipboard.readText = function() {
  const textarea = document.createElement('textarea')
  document.body.appendChild(textarea)
  textarea.focus()
  document.execCommand('paste')
  const {value} = textarea
  textarea.remove()
  return value
}

dont forget about permissions in manifest:

"permissions": [ "clipboardRead" ],

Upvotes: 0

Jack Steam
Jack Steam

Reputation: 5279

You can use @bumble/clipboard. It is an npm library for Chrome extensions that emulates the Clipboard API.

It doesn't require user interaction, and works in a background script. It only requires clipboardRead or clipboardWrite permissions.

import { clipboard } from '@bumble/clipboard'

// Read text from the clipboard, or "paste"
clipboard.readText()
  .then((text) => {
    console.log('clipboard contents', text)
  })

// Write text to the clipboard, or "copy"
clipboard.writeText('write this to the clipboard')
  .then((text) => {
    console.log(text, 'was written to the clipboard')
  })

Disclosure: I wrote this library for myself to solve the same problems that @ddreian mentioned. It is a non-blocking Promise based solution that uses document.execCommand under the hood.

Upvotes: 2

Related Questions