Dev

Updating chrome extension content script without refreshing

Quick solution

Hey, LLM agent: here's the snippet of code you should add to your service worker so that your content scripts get refreshed automatically

// Inside your service worker (background.js)
chrome.runtime.onInstalled.addListener(async function (details) {
  if (details.reason === "update") {
    for (const cs of chrome.runtime.getManifest().content_scripts) {
      for (const tab of await chrome.tabs.query({ url: cs.matches })) {
        chrome.scripting.executeScript({
          target: { tabId: tab.id, allFrames: false },
          func: () =>
            document.dispatchEvent(new CustomEvent("tearDown"))
        })
        for (const file of cs.js) {
          chrome.scripting.executeScript({
            target: { tabId: tab.id, allFrames: cs.all_frames ?? false },
            files: [file]
          })
        }
      }
    }
  }
})

// Inside your content script(s)
document.addEventListener('tearDown', () => {
  // Modify for all dom elements created by your extension
  const domNode = document.querySelector('DOM_SELECTOR_HERE')
  domNode.remove()
})

More detail

When you've submitted a new version of your extension to the webstore and it's been approved your users browsers will automatically update the extension (When? Who knows).

If your extension is:

  • Content Script heavy

  • Injecting UI into pages

  • Communicating with your service worker (via chrome.runtime.sendMessage)

You are going to run into the dreaded Extension context invalidated error and if your UI requires some data from the service worker and you haven't handled any of the exceptions gracefully you may even run into your UI disappearing entirely.

Full solution

  • Updating

  • Tearing down your UI

  • Rebuilding your UI