如何在Chrome扩展程序中使用navigator.clipboard.readText()? [英] How can I use navigator.clipboard.readText() in a Chrome extension?

查看:1606
本文介绍了如何在Chrome扩展程序中使用navigator.clipboard.readText()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个Firefox扩展程序,它读取剪贴板,并且如果它具有一些PEM证书,它将在新选项卡中打印其详细信息.我正在尝试移植到Chrome.这没用.我在做什么错了?

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?

我要求剪贴板在manifest.json中读取内容,并在后台脚本中运行它,并且在Firefox中运行良好.

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
 });

这在Chrome中失败,并显示无法在'剪贴板'上执行'readText':非法调用".我究竟做错了什么?如何在Chrome浏览器中也可以使用此功能?大多数答案涉及创建输入,获得焦点,执行粘贴.那真的很复杂,我希望我不必这样做.它在Firefox中确实能很好地工作,为什么在Chrome中会变得复杂?

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?

推荐答案

您可以使用 @bumble/clipboard .这是一个用于Chrome扩展程序的npm库,它模仿剪贴板API.

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

它不需要用户交互,并且可以在后台脚本中工作.它只需要clipboardReadclipboardWrite权限.

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')
  })

公开:我为自己编写了这个库,以解决@ddreian提到的相同问题.这是一个基于Promise的无阻塞解决方案,在后台使用了document.execCommand.

这篇关于如何在Chrome扩展程序中使用navigator.clipboard.readText()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆