我将遵循 wOxxOm 给您的出色建议,并通过具体示例对其进行详细说明。您想要做的是让 ContentScript.js 在任何带有网页的活动选项卡上运行,因为您无法从 backGround.js 访问 DOM,然后向此脚本发送消息,您可以从其中复制到剪贴板。
清单.json
"background" :{
"service_worker" :"eventPage.js"
},
"permissions" : [
"contextMenus",
"clipboardWrite"
],
"content_scripts": [ // this is what you need to add
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
从background.js,您将发送一条消息,该消息将在ContentScript.js中处理
背景.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id,
{
message: "copyText",
textToCopy: "some text"
}, function(response) {})
})
在 contentScript.js 中,您将捕获消息并将其复制到剪贴板。
内容.js
chrome.runtime.onMessage.addListener( // this is the message listener
function(request, sender, sendResponse) {
if (request.message === "copyText")
copyToTheClipboard(request.textToCopy);
}
);
async function copyToTheClipboard(textToCopy){
const el = document.createElement('textarea');
el.value = textToCopy;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}