2012-11-12 161 views
7

我想整天有这样的工作,我不能...... 我曾尝试: - Flash版本(至少3级不同的) - document.execCommand(”复制“)在内容脚本,但也在后台页面 我检查了stackoverflow上的许多页面...每一个可用的解决方案。复制到Chrome浏览器扩展剪贴板

有没有人有一个工作的例子?

编辑:

的manifest.json

{ 
    "name": "test", 
    "manifest_version": 2, 
    "version": "1.0", 
    "description": "test", 
    "content_scripts": [{ 
      "matches": ["https://somesite.com*"], 
      "js": ["jquery.js", "script.js"], 
      "run_at": "document_end", 
      "css": ["style.css"] 
    }], 
    "permissions": [ 
      "clipboardWrite", 
      "clipboardRead" 
    ] 
} 

的script.js

$(document).ready(function() { 
    $('body').append('<textarea id="test"/>'); 
    var $test = $('#test'); 
    $test.text('some text which should appear in clipboard'); 
    $test.select(); 
    document.execCommand('copy'); 
    alert('copied!'); 
}); 

以上不起作用。警报显示...

编辑2: 我也尝试过使用闪存版本,但它可能不工作,因为该扩展是在本地主机上运行的东西,我认为。

回答

7

复制奇怪地工作。您应该为该副本注册事件侦听器,然后在执行document.execCommand('copy')时调用该事件侦听器。

这是事件处理程序的工作示例:

document.addEventListener('copy', function(e) { 
    var textToPutOnClipboard = "some text which should appear in clipboard"; 
    e.clipboardData.setData('text/plain', textToPutOnClipboard); 
    e.preventDefault(); 
}); 
3

确保您已在manifest.json中得到了复制权限:

"permissions": [ 
    "clipboardWrite", // for copy and cut 
    "clipboardRead", // for paste 

], 

然后用document.execCommand('copy')东西一旦选择

更多信息here

+0

另外THX的帮助,你看在我的代码(见编辑问题)出问题了吗? – mrzepa

相关问题