In short, I want that when you press my extension button from the context menu, the content script will be added to the web page temporarily. I tried to use sendMessage() but it just didn't work.
Any help will be appreciated:)
//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"]
}
]
}
so I tried to use chrome.scripting but failed. that's what I came up with:
//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>"],