【问题标题】:How can I use navigator.clipboard.readText() in a Chrome extension?如何在 Chrome 扩展程序中使用 navigator.clipboard.readText()?
【发布时间】:2019-01-27 08:19:19
【问题描述】:

我写了一个 Firefox 扩展来读取剪贴板,如果它有一些 PEM 证书,它会在新标签中打印它的详细信息。我正在尝试移植到 Chrome。这没用。我做错了什么?

我在 manifest.json 中请求了 clipboardRead,我在后台脚本中运行它,它在 Firefox 中运行良好。

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

这在 Chrome 中失败,并显示“无法在 'Clipboard' 上执行 'readText':非法调用”。我究竟做错了什么?我怎样才能在 Chrome 中也能做到这一点?大多数答案涉及创建输入、获得焦点、执行粘贴。这真的很复杂,我希望我不必这样做。在火狐上运行得很好,为什么在 Chrome 里就复杂了?

【问题讨论】:

标签: google-chrome firefox google-chrome-extension firefox-addon-webextensions


【解决方案1】:

您可以使用@bumble/clipboard。它是一个模拟剪贴板 API 的用于 Chrome 扩展的 npm 库。

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

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

【讨论】:

  • 这不能回答问题What am I doing wrong? How can I make this work in Chrome also? 此外,您的库使用oldschool document.execCommand 而不是包装剪贴板API。
  • 如果最终目标是在 Chrome 扩展程序中使用像剪贴板 API 一样工作的 API,则此答案有效。如果最终目标是在 Chrome 扩展背景页面中使用 actual Clipboard API,那么您是正确的。在这种情况下,这个问题没有答案,因为剪贴板 API 需要用户交互,而这在 Chrome 扩展程序背景页面中是不可能的。
  • @JackSteam 您的解决方案无法在 ManifestV3 上运行,原因是服务人员。
  • @titusfx 正确。此答案适用于 MV2。目前没有办法在 MV3 中使用剪贴板 API,除了在 HTML 页面中,例如选项或弹出页面。
猜你喜欢
  • 2013-02-04
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多