2014-03-28 93 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;