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

前端 未结 1 556
无人共我
无人共我 2021-01-22 00:08

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 wor

相关标签:
1条回答
  • 2021-01-22 01:00

    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.

    0 讨论(0)
提交回复
热议问题