Jonghakseo / chrome-extension-boilerplate-react-vite

Chrome Extension Boilerplate with React + Vite + Typescript
MIT License
2.26k stars 329 forks source link

Question: How to implement content script re-injection? #677

Closed chanan closed 1 month ago

chanan commented 1 month ago

When the extension is first installed the content script is not started till a tab is refreshed. This stack overflow describes a solution: https://stackoverflow.com/questions/10994324/chrome-extension-content-script-re-injection-after-upgrade-or-install

Which is basically this:

chrome.runtime.onInstalled.addListener(async () => {
  for (const cs of chrome.runtime.getManifest().content_scripts) {
    for (const tab of await chrome.tabs.query({url: cs.matches})) {
      if (tab.url.match(/(chrome|chrome-extension):\/\//gi)) {
        continue;
      }
      chrome.scripting.executeScript({
        files: cs.js,
        target: {tabId: tab.id, allFrames: cs.all_frames},
        injectImmediately: cs.run_at === 'document_start',
        // world: cs.world, // uncomment if you use it in manifest.json in Chrome 111+
      });
    }
  }
});

My question is - how can that be implemented, specifically, regarding the files names in the script above.

github-actions[bot] commented 1 month ago

Thank you for your contribution. We will check and reply to you as soon as possible.

Jonghakseo commented 1 month ago

Maybe it would be helpful for you to run pnpm build and check the names of the files created in the dist folder?

chanan commented 1 month ago

I miss read the javascript - file names are not needed. Here is the version that makes typescript happy:

chrome.runtime.onInstalled.addListener(async () => {
  for (const cs of chrome.runtime.getManifest().content_scripts || []) {
    for (const tab of await chrome.tabs.query({ url: cs.matches })) {
      if (!tab.url || tab.url.match(/(chrome|chrome-extension):\/\//gi)) {
        continue;
      }
      chrome.scripting.executeScript({
        files: cs.js || [],
        target: { tabId: tab.id!, allFrames: cs.all_frames },
        injectImmediately: cs.run_at === 'document_start',
        //world: cs.world,
      });
    }
  }
});