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

时间:2014-03-28 01:18:29

标签: javascript google-chrome google-chrome-extension clipboard

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

4 个答案:

答案 0 :(得分:19)

基本上,您可以使用document.execCommand('paste|copy|cut')操纵剪贴板。

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

      

    " clipboardRead"如果扩展程序或应用程序使用document.execCommand('粘贴'),则为必需。

         

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

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

  • 把重点放在它上面
  • 致电document.execCommand('paste')
  • <input> value属性中获取字符串。

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

答案 1 :(得分:8)

要在Chrome扩展程序中阅读剪贴板文字,您必须:

  • request&#34; clipboardRead&#34;您的清单中的权限
  • 创建后台脚本,因为只有后台脚本可以访问剪贴板
  • 在后台页面中创建一个元素以接受剪贴板粘贴操作。如果你把它作为textarea,你将获得纯文本,如果你使用contentEditable = true的div,你将获得Formatted 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 :(得分:1)

这是一个非常简单的解决方案。它只需要您的权限即可包含"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扩展程序中有效,而在网页中无效。

答案 3 :(得分:0)

我发现的最佳可行示例是here

function getClipboard() {
    var result = null;
    var textarea = document.getElementById('ta');
    textarea.value = '';
    textarea.select();

    if (document.execCommand('paste')) {
        result = textarea.value;
    } else {
        console.error('failed to get clipboard content');
    }

    textarea.value = '';
    return result;
}
相关问题