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

28

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

4个回答

34

你可以使用 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属性中获取字符串。

对我来说,这可用于将数据复制到剪贴板。


我可以使用“粘贴”从剪贴板中提取数据吗? - schumacherj
是的,它应该可以工作。我已经更新了答案。否则我不明白为什么Chrome需要“clipboardWrite”权限。 - Ivan Nevostruev
1
粘贴剪贴板内容需要读取剪贴板的权限,而不是写入权限。我更新了答案。为了让它更清晰:如果你想复制到剪贴板,你需要写入权限。 - Jacopo Penzo
添加了两个示例。 - Jacopo Penzo

17
为了在Chrome扩展程序中读取剪贴板文本,您需要:
  • 在您的清单文件中请求"clipboardRead"权限
  • 创建一个后台脚本,因为只有后台脚本可以访问剪贴板
  • 在您的后台页面中创建一个元素以接受剪贴板粘贴操作。如果您将其设置为textarea,则会获得纯文本,如果将其设置为带有contentEditable=true的div,则会获取格式化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;

2
在 background.js 中,您不需要获取和使用变量 bg,只需使用 document。 - Jan Croonen

8

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

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

请注意,在Chrome浏览器中,document.execCommand("paste") 被禁用,只能在Chrome扩展程序中使用,而不能在网页中使用。

4
我发现最好的可行示例在这里,下面的示例适用于我,我分享在这里以便有人可以获得帮助。
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接