Clipboard Copy / Paste on Content script (Chrome Extension)

笑着哭i 提交于 2019-11-28 21:35:55

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();
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!