如何在Chrome扩展中获取剪贴板数据

How to get Clipboard data in Chrome Extension?

本文关键字:获取 剪贴板 数据 扩展 Chrome      更新时间:2023-09-26

我很难找到任何关于如何添加"Ctrl+C"侦听器的最新信息,获取剪贴板数据,然后在Chrome扩展中写回剪贴板。我找到的所有旧代码都是针对现在已弃用的旧版本。

基本上你可以使用document.execCommand('paste|copy|cut')来操作剪贴板。

  • 您需要在清单中指定"clipboardWrite"和/或"clipboardRead"权限。

    "clipboardRead"当扩展名或应用程序使用document.execCommand('paste')时必须。

    "clipboardWrite"表示扩展名或应用程序使用document.execCommand('copy')或document.execCommand('cut')。托管应用程序需要此权限;推荐用于扩展和打包的应用。

  • 创建<input>元素(或<textarea>)

  • 把焦点放到
  • 呼叫document.execCommand('paste')
  • <input> value属性中抓取字符串

我可以把数据复制到剪贴板

为了在chrome扩展中读取剪贴板文本,您必须:

  • 请求"clipboardRead"在清单中的权限
  • 创建一个背景脚本,因为只有背景脚本可以访问剪贴板
  • 在你的背景页面中创建一个元素来接受剪贴板的粘贴动作。如果你把它设为textarea,你会得到纯文本如果你把它设为div并设置contentteditable =true,你会得到格式化的HTML
  • 如果你想把剪贴板数据传递回页面内脚本,你需要使用消息传递API

要查看所有这些工作的示例,请参阅我的BBCodePaste扩展:

https://github.com/jeske/BBCodePaste

下面是如何在背景页中读取剪贴板文本的一个示例:

bg = chrome.extension.getBackgroundPage();        // get the background page
bg.document.body.innerHTML= "";                   // clear the background page
// add a DIV, contentEditable=true, to accept the paste action
var helperdiv = bg.document.createElement("div");
document.body.appendChild(helperdiv);
helperdiv.contentEditable = true;
// focus the helper div's content
var range = document.createRange();
range.selectNode(helperdiv);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
helperdiv.focus();    
// trigger the paste action
bg.document.execCommand("Paste");
// read the clipboard contents from the helperdiv
var clipboardContents = helperdiv.innerHTML;

这里有一个非常简单的解决方案。它只需要您的权限包含"clipboardRead""clipboardWrite"copyTextToClipboard函数取自这里:https://stackoverflow.com/a/18455088/4204557

var t = document.createElement("input");
document.body.appendChild(t);
t.focus();
document.execCommand("paste");
var clipboardText = t.value; //this is your clipboard data
copyTextToClipboard("Hi" + clipboardText); //prepends "Hi" to the clipboard text
document.body.removeChild(t);

请注意,document.execCommand("paste")是在Chrome禁用,将只工作在Chrome扩展,而不是在一个网页。

我找到的最佳可行示例如下下面的例子对我来说很有效,分享给大家,以便大家得到帮助

function getClipboard() {
    var result = null;
    var textarea = document.getElementById('ta');
    textarea.value = '';
    textarea.select();
    if (document.execCommand('paste')) {
        result = textarea.value;
    } else {
        console.log('failed to get clipboard content');
    }
    textarea.value = '';
    return result;
}