2

我正在尝试阅读Google Chrome扩展中的剪贴板文本。到目前为止,我已经尝试过使用这些代码,并且它返回给我的是未定义的。请帮助我。如何阅读谷歌Chrome扩展中的剪贴板文本

在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); 
}); 
+1

[为什么document.execCommand('paste')不能在我的扩展中工作](http://stackoverflow.com/questions/8503738/why-document-execcommandpaste-is-not-working-in -my-extension) – pimvdb 2011-12-14 18:29:23

回答

0

为了在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;