简而言之,我希望当您按下上下文菜单中的“我的扩展”按钮时,内容脚本将临时添加到网页中。我试着使用sendMessage(),但是它没有起作用。
(如有任何帮助,将不胜感激:)
//This is the service worker (eventPage)
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'select',
title: 'select',
type: 'normal',
contexts: ['all']
});
})
chrome.contextMenus.onClicked.addListener(function(clickDate) {
if (clickDate.menuItemId == 'select') {
//send message to make content-script start operate
chrome.runtime.sendMessage('start');
}
});//let's say that this is the content-script
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
if (response == 'start') {
// js code that is inserted into the site
}
});{
"manifest_version": 3,
"name": "SendFast",
"description": "This extension makes it easier to send information",
"version": "1.0",
"icons": {
"128": "16-nahum.png",
"48": "64-nahum.png",
"16": "16-nahum.png"
},
"action": {
"default_icon": "16-nahum.png",
"default_popup": "popup.html"
},
"permissions":["contextMenus","activeTab"],
"background":{
"service_worker": "eventPage.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-script.js"]
}
]}
所以我试着使用chrome.scripting,但是失败了。这就是我想出来的:
//eventPage.js(after changes)
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'select',
title: 'select',
type: 'normal',
contexts: ['all']
});
})
async function addJsScript() {
const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
await chrome.scripting.executeScript({
target: {tabId: tab.id},
script:["content-script"],
});
}
chrome.contextMenus.onClicked.addListener(function(clickDate) {
if (clickDate.menuItemId == 'select') {
addJsScript()
}
});我把这个加到了舱单上:
"permissions":["contextMenus","activeTab","scripting"],
"host_permissions":["<all_urls>"],发布于 2022-05-22 04:23:32
有几个问题,我一直以来都是与此有关的。这是你需要知道的。
首先,要访问选项卡,需要将"host_permissions": ["<all_urls>"]添加到清单(v3)中,以确保可以访问网页。
第二,使用script:["content-script.js"]代替在addJsScript()函数中看到的files:["content-script.js"]。
最后,确保在清单文件中添加了scripting权限。
这就是我为我修理它所必须做的。
另外,如前所述,从清单中删除内容脚本,并将.js添加到files脚本名称的末尾。
https://stackoverflow.com/questions/70640115
复制相似问题