Clipboard Copy / Paste on Content script (Chrome Extension)

后端 未结 1 1030
暖寄归人
暖寄归人 2020-12-14 22:51

I am using a Content script to manipulate data in the DOM. I have been using document.execCommand(\'copy\'); successfully on a popup page.

I am now searchin

相关标签:
1条回答
  • 2020-12-14 22:58

    Content scripts cannot use the clipboard at the moment. In the future, once crbug.com/395376 is resolved, then the code as shown in the question will work as intended.

    Until that bug is fixed, you have to send the data to the background page and copy the text from there:

    // content script
    chrome.runtime.sendMessage({
        type: 'copy',
        text: 'some text to copy'
    });
    

    Script on background page or event page:

    chrome.runtime.onMessage.addListener(function(message) {
        if (message && message.type == 'copy') {
            var input = document.createElement('textarea');
            document.body.appendChild(input);
            input.value = message.text;
            input.focus();
            input.select();
            document.execCommand('Copy');
            input.remove();
        }
    });
    
    0 讨论(0)
提交回复
热议问题