"the proper use of execcommand(“paste”) in a chrome extension" Code Answer

2

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();
    document.execcommand('copy');
    sandbox.val('');
}

function paste() {
    var result = '',
        sandbox = $('#sandbox').val('').select();
    if (document.execcommand('paste')) {
        result = sandbox.val();
    }
    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.

By Nimsrules on April 30 2022

Answers related to “the proper use of execcommand(“paste”) in a chrome extension”

Only authorized users can answer the Search term. Please sign in first, or register a free account.