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

mrz*_*epa 9 google-chrome-extension

我正在努力让这一切工作,我不能......我尝试过: - flash版本(至少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"
    ]
}
Run Code Online (Sandbox Code Playgroud)

的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!');
});
Run Code Online (Sandbox Code Playgroud)

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

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

Ste*_*ell 9

复制工作很奇怪.您应该为该副本注册一个事件监听器,然后在执行此操作时将调用该监听器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();
});
Run Code Online (Sandbox Code Playgroud)


Kir*_*lev 6

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

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

],
Run Code Online (Sandbox Code Playgroud)

然后document.execCommand('copy')在选择某项后使用

更多信息在这里