Search code examples
javascriptgoogle-chrome-extension

Chrome Extension V3 - Service Worker Confusion


Never made a Chrome extension before. I'm confused about the service workers. All I want to do is when a user clicks on the extension icon, is to run some JavaScript that manipulates the DOM. I do have my background.js script identified as a service worker.

    "background": {
        "service_worker": "./background.js"
    },

What I don't understand (after watching a bunch of Youtube videos) is how my background.js file should be structured? I just want it to load my content.js file. I have some mocked up example below to give an idea.

chrome.tabs.[some api event]((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete') {
        chrome.scripting.executeScript({
            target: { tabId: tabId },
            files: ["./content.js"
        })
    }
});

I have no idea what to do in the service worker file? Do I just register the service worker and then execute my content.js file? Not even sure which event would be the correct one to use in the API to just run my content.js? Any input or links to pages to help me understand this further would be greatly appreciated.


Solution

  • You need chrome.action API and its onClicked event + executeScript, not chrome.tabs.

    manifest.json:

      "action": {"default_title": "Click me"},
      "background": {"service_worker": "background.js"},
      "permissions": ["scripting", "activeTab"],
    

    background.js (registered automatically, no need to do it explicitly).

    chrome.action.onClicked.addListener(tab => {
      chrome.scripting.executeScript({
        target: {tabId: tab.id},
        files: ['content.js'],
      });
    });
    

    content.js:

    // here you can access the web page DOM
    console.log('Yay');