Search code examples
javascriptjsongoogle-chrome-extension

connect a service worker to a content script


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()
  
  }
});
and i added this to the manifest:

    "permissions":["contextMenus","activeTab","scripting"],
"host_permissions":["<all_urls>"],

Solution

  • There are a few problems that I have been having that is related to this. Here's what you need to know.

    First, to access the tabs, you need to add "host_permissions": ["<all_urls>"] to your manifest (v3) to assure that you can access the web pages.

    Second, instead of script:["content-script.js"] as seen in the addJsScript() function, use files:["content-script.js"].

    Lastly, make sure you have the scripting permission added in your manifest file.

    That is what I had to do to fix it for me.

    Also, as stated above, remove the content script from your manifest and add .js to the end of the script name in files