Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy to clipboard in chrome extensions

I'm trying all day to have this working and I can't... I have tried: - flash versions (at least 3 different ones) - document.execCommand("copy") in content script, but also in background page I've checked numerous pages on stackoverflow... every available solution.

Does anyone have a working example?

EDIT:

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

Above doesn't work. Alert is shown...

EDIT2: I've also tried with flash versions, but it possibly doesn't work because of that extension is something that is run on localhost, I think.

like image 736
mrzepa Avatar asked Nov 12 '12 18:11

mrzepa


People also ask

How do I enable copy to clipboard in Chrome?

To Enable Shared Clipboard In Google Chrome, Open the Google Chrome browser. Type the following text in the address bar: chrome://flags#shared-clipboard-receiver . Select Enabled from the drop down list next to the Enable receiver device to handle shared clipboard feature option.

How do I copy from Chrome clipboard?

To copy text, highlight the section of text you want and use. Then hit Ctrl+C to copy and save it to the clipboard.

How do I enable copy and paste extensions?

Enable copy paste on websites that have disabled copy paste. How to use: - Click on the extension icon - After a popup is opened, use the “Enable copy paste for all websites” checkbox. - Manually refresh the page and see if the extension has successfully enabled copy paste functionality on the website.


1 Answers

Copy works strangely. You should register an event listener for the copy, then this will be called when you do the document.execCommand('copy').

This is a working example of the event handler:

document.addEventListener('copy', function(e) {
  var textToPutOnClipboard = "some text which should appear in clipboard";
  e.clipboardData.setData('text/plain', textToPutOnClipboard);
  e.preventDefault();
});
like image 100
Steve Campbell Avatar answered Oct 10 '22 03:10

Steve Campbell