2014-03-28 91 views

回答

13

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

  • 您需要在清單中指定"clipboardWrite"permissions
  • 創建<input>元素(或<textarea>
  • 認沽重點是
  • 呼叫document.execCommand('paste')
  • 抓住你的字符串從<input>value屬性。

這適用於我複製數據到剪貼板。

+0

我可以使用「粘貼」從剪貼板中提取數據嗎? – schumacherj

+0

是的,它應該工作。我已經更新了答案。否則,我不明白爲什麼chrome需要'clipboardWrite'權限。 –

+0

它不適合我... – ihorko

3

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