Search code examples
javascriptreactjsgoogle-chrome-extensionservice-workerchrome-extension-manifest-v3

Chrome extension service workers stops listening to events after opening popup


I'm developing a chrome extension with MV3.

I've encountered an issue in which when I open the popup when clicking on the extension's icon the service worker background script stops receiving the chrome.tabs.onUpdated events, even after I close the popup. The only way I can make it work again is by reloading the extension.

I will mention that the popup that I'm rendering is a react app, not sure if it has to do with the issue, but when I swap the popup content to a normal HTML with just a button or something it is working as expected

Basically what I'm trying to do in the extension is listen to chrome.tabs.onUpdated event to detect URL changes in the background script, and send a message to a content script in order to save some data to the chrome local storage.

This is the manifest.json -

{
  "name": "My Extension",
  "description": "Extension POC",
  "version": "0.0.0.1",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["tabs", "storage", "activeTab"],
  "action": {
    "default_popup": "build\\index.html",
    "default_title": "Open Pane",
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

And this is the background.js -

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    if (!isPageDoneLoading(changeInfo)) {
        return;
    }
    const url = tab.url;
    const ticketId = url.substring(url.lastIndexOf("/") + 1);
    if (isTargetURL(url) && !isNaN(ticketId)) {
        // Update the ID only if it doesn't equal to the previous one or if null
        if (!CURRENT_TICKET_ID || CURRENT_TICKET_ID !== ticketId) {
            CURRENT_TICKET_ID = ticketId;   
            
            const props = getProperties(ticketId);
            chrome.tabs.sendMessage(tabId, { action: {ticketId, props: props}  });
        }
    }
})

Any idea what may be the root cause or how can I resolve the issue?


Solution

  • What React version are you using? In the older React version, part of the create-react-app script creates a file called serviceWorker.js. and a call to it in index.js. When I created a new project with a newer React version, 18.X.X it didn't create this file. I suppose there is some conflict with the service worker of the chrome extension and the one react app created.