2011-12-14 49 views
2

我正在创建一个可以读取剪贴板内容的Google Chrome扩展。
但我无法得到这个文件。我想要在IE的剪贴板API中获得剪贴板内容。
在manifest文件中我给的权限为什么document.execCommand('paste')在我的扩展中不起作用

clipboardRead and clipboardWrite. 

我已经创造了后台页面的功能如下

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); 
}); 
功能

但是,这返回给我undefined ...

+0

[如何阅读Chrome浏览器扩展中的剪贴板文本](http:/ /stackoverflow.com/questions/8509670/how-to-read-the-clipboard-text-in-google-chrome-extension) –

回答

1
var str = document.execCommand('paste'); 

您还需要添加clipboardReadpermission

+0

嘿,它返回True而不是剪贴板!代码与上面相同,我给了权限,我做错了什么? – espectalll

+0

矿还返回true以及...似乎像execCommand()根本没有返回一个字符串:http://help.dottoro.com/ljcvtcaw.php它似乎从字面上调用粘贴命令。这看起来像一个解决方法:http://stackoverflow.com/questions/7144702/the-proper-use-of-execcommandpaste-in-a-chrome-extension –

0

document.execCommand('paste')返回成功或失败,而不是剪贴板的内容。

该命令触发一个粘贴操作到背景页面中的焦点元素。您必须在后台页面中创建TEXTAREA或DIV contentEditable = true并将其聚焦以接收粘贴内容。

你可以看到如何使这项工作在我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; 

如果你想用纯文本代替HTML,你可以使用helperdiv.innerText,或者你可以切换到使用textarea。如果你想以某种方式解析HTML,你可以走在DIV里面的HTML DOM(再次看到我的BBCodePaste扩展)

相关问题