7

I want to write some data in to clipborad from a chrome extension which I'm creating. In the manifest file i gave permissions to both clipboardRead and clipboardWrite.

i use this function which i found here

but it doesn't work. seems that "document.execCommand('copy');" can not work.

i write all of these codes in content script.

thx manifest:

{
    "manifest_version":2,

    "name":"easyCopy",
    "description":"just a small toll",
    "version":"1.0.0",

    "permissions":[
        "clipboardWrite", "http://*/*", "clipboardRead"
    ],

    "content_scripts":[
        {
            "matches":["http://*/*"],
            "js":["jquery-1.9.1.min.js", "main_feature.js"]
        }
    ],

    "background":{
        "persistent":false,
        "page":"background.html"
    }
}

main_feature.js:

copyOrderId();
function copyOrderId() {
    $(".order-num").click(function () {
        var curOrderNum = $(this).text();
        copyTextToClipboard(curOrderNum);
//        chrome.extension.sendMessage({method:"copy", content:curOrderNum}, function (response) {
//            clog(response);
//        });
    });


}

function copyTextToClipboard(text) {
    var copyFrom = $('<textarea/>');
    copyFrom.text(text);
    $('body').append(copyFrom);
    copyFrom.select();
    document.execCommand('copy', true);
    copyFrom.remove();

}
function clog(message) {
    console.log(message);
}

the background.html is just a blank page with basic html body.

Community
  • 1
  • 1
Hank X
  • 1,988
  • 2
  • 14
  • 32

1 Answers1

8

Thanks everyone, I ended up using this:

document.execCommand can not work in content script. Instead, I send data to background page and then run the "copyTextToClipboard" function.

Notice that you must put your JavaScript into single .js file instead of mixing it with background.html.

Additionally, the textarea must have an id or class property.

nickd
  • 3,951
  • 2
  • 20
  • 24
Hank X
  • 1,988
  • 2
  • 14
  • 32
  • can you clarify further? if I define a hidden field in my content script based js file, can I acces its value in background for copy purpose? – Volatil3 Dec 04 '13 at 18:30
  • @Volatil3 :Sorry, I didn't see your comment. Define a hidden field in you background, then you can copy it. if you want to copy any thing in the content script, you have to send the data to background with MessagePassing api of chrome. – Hank X Jan 03 '14 at 02:50
  • 1
    This bug has been fixed in Chrome 39 - see https://code.google.com/p/chromium/issues/detail?id=395376 – Rob W Sep 11 '14 at 10:17