2011-12-14 45 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擴展)

相關問題