如何阅读谷歌浏览器扩展中的剪贴板文本

时间:2011-12-14 18:22:06

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

我正在尝试在Google Chrome扩展程序中阅读剪贴板文字。到目前为止,我已尝试使用tis代码,它返回我未定义。请帮帮我。

在background.html中,我的代码是

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
 if (request.method == "getClipData")
   sendResponse({data: document.execCommand('paste')});
 else
   sendResponse({}); // snub them.
 });

在我的内容脚本中,我的代码是

chrome.extension.sendRequest({method: "getClipData"}, function(response) {
   alert(response.data);
});

2 个答案:

答案 0 :(得分:2)

曾几何时有一个实验性的API chrome.experimental.clipboard,但不再有http://code.google.com/chrome/extensions/trunk/experimental.clipboard.html

也许你应该尝试:How do I copy to the clipboard in JavaScript?

更新: 我错了 - 有可能。正如permissions page所说,有“clipboardRead”和“clipboardWrite”权限。所以也许他们会为你工作。

答案 1 :(得分:0)

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

  • 请求清单中的“clipboardRead”权限
  • 创建后台脚本,因为只有后台脚本可以访问剪贴板
  • 在后台页面中创建一个元素以接受剪贴板粘贴操作。如果你把它作为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;
相关问题