monopoint monopoint - 1 year ago 493
Javascript Question

the proper use of execcommand("paste") in a chrome extension

I'm trying to paste clipboard data into a textarea using

with a chome extension, but i cannot seem to get it to work.
permissions are set.
I have tried to set
on the textarea, but
does nothing, and I get no error.
from background page also does nothing.

<textarea id="ta"></textarea>
<script type="text/javascript">

Answer Source

Clipboard functionality is a key part of my extension so I've seen all the normal problems. On my background page I expose a copy and a paste function and the page itself contains <textarea id="sandbox"></textarea>;

function copy(str) {
    var sandbox = $('#sandbox').val(str).select();

function paste() {
    var result = '',
        sandbox = $('#sandbox').val('').select();
    if (document.execCommand('paste')) {
        result = sandbox.val();
    return result;

I'm using jQuery for simplicity but you get the idea. Now any time I want to use the clipboard functionality I simply call the relevant function. Other pages in my extension can access this API via chrome.extension.getBackgroundPage() but you can also use chrome.runtime.getBackgroundPage(callback) if your background page is an event page.

I'm not sure if this is best practice or if such a thing even exists for this functionality yet but this definitely works for me and is very clean.