如何在 Chrome 扩展中使用 navigator.clipboard.readText()?
How can I use navigator.clipboard.readText() in a Chrome extension?
我写了一个读取剪贴板的 Firefox 扩展,如果它有一些 PEM 证书,它会在新选项卡中打印它的详细信息。我正在尝试移植到 Chrome。这没用。我做错了什么?
我在 manifest.json 中请求剪贴板读取,我在后台脚本中 运行 它在 Firefox 中工作正常。
navigator.clipboard.readText().then(function (textFromClipboard) {
//do stuff with textFromClipboard
});
这在 Chrome 和 "Failed to execute 'readText' on 'Clipboard': Illegal invocation" 中失败了。我究竟做错了什么?我怎样才能在 Chrome 中也进行这项工作?大多数答案涉及创建输入、获取焦点、执行粘贴。这真的很复杂,我希望我不必这样做。它在 Firefox 中运行良好,为什么在 Chrome 中变得复杂?
您可以使用 @bumble/clipboard
。它是一个用于 Chrome 扩展的 npm 库,模拟剪贴板 API。
它不需要用户交互,并且在后台脚本中运行。它只需要 clipboardRead
或 clipboardWrite
权限。
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
。
我写了一个读取剪贴板的 Firefox 扩展,如果它有一些 PEM 证书,它会在新选项卡中打印它的详细信息。我正在尝试移植到 Chrome。这没用。我做错了什么?
我在 manifest.json 中请求剪贴板读取,我在后台脚本中 运行 它在 Firefox 中工作正常。
navigator.clipboard.readText().then(function (textFromClipboard) {
//do stuff with textFromClipboard
});
这在 Chrome 和 "Failed to execute 'readText' on 'Clipboard': Illegal invocation" 中失败了。我究竟做错了什么?我怎样才能在 Chrome 中也进行这项工作?大多数答案涉及创建输入、获取焦点、执行粘贴。这真的很复杂,我希望我不必这样做。它在 Firefox 中运行良好,为什么在 Chrome 中变得复杂?
您可以使用 @bumble/clipboard
。它是一个用于 Chrome 扩展的 npm 库,模拟剪贴板 API。
它不需要用户交互,并且在后台脚本中运行。它只需要 clipboardRead
或 clipboardWrite
权限。
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
。