google-chromefirefoxgoogle-chrome-extensionfirefox-addon-webextensions

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?


Solution

  • 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.