在Chrome扩展程序中复制到剪贴板

时间:2012-11-12 18:30:25

标签: google-chrome-extension

我正在努力工作,我不能...... 我试过了: - 闪光版(至少3种不同版本) - document.execCommand(“copy”)在内容脚本中,但也在后台页面中 我已经在stackoverflow上检查了很多页面...每个可用的解决方案。

有没有人有一个有效的例子?

编辑:

的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!');
});

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

EDIT2: 我也试过使用flash版本,但它可能不起作用,因为我认为扩展是在localhost上运行的。

2 个答案:

答案 0 :(得分:8)

复制工作很奇怪。您应该为副本注册一个事件监听器,然后在执行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();
});

答案 1 :(得分:4)

确保您在manifest.json中拥有复制权限:

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

],

然后在选择某些内容后使用document.execCommand('copy')

更多信息here