Manifest V3, background service worker and popup.html

1,711 views
Skip to first unread message

Laurence Lewis

unread,
Jun 25, 2022, 5:12:33 AM6/25/22
to Chromium Extensions
If I use a background.js service worker to inject js into the web page. 

chrome.action.onClicked.addListener(async tab => { try { await chrome.scripting.executeScript({ target: { tabId: tab.id, allFrames: true, }, files: ["script.js"], }); } catch (erri) { console.error(`failed to execute script: ${erri}`); } });

The javascript is loaded. I can see this working because it adds a class to the document body.  

However,

If I add a popup.html to the manifest, that opens a popup with a checkbox when the extension button is clicked, the background.js service worker no longer injects the script and the class  is not added to the document body. 

I can’t work out why. 

I’d appreciate some guidance how to inject the script into the document (web page) and also be able to have the popup functionality. 

Regards
Laurence 

wOxxOm

unread,
Jun 25, 2022, 7:29:47 AM6/25/22
to Chromium Extensions, laurence...@gmail.com
It's because having a popup (e.g. declared via `default_popup`) disables onClicked event so you'll have to put all the code in the popup script.

I'd say it's a bad design of the API for several reasons: timing, predictability, and awareness. The surprising quirkiness of this behavior has been confusing to a lot of people for the past decade. You can suggest the the browser at least prints a warning in the background console when onClicked is used together with default_popup on https://crbug.com, btw.  As for timing, there's no way to run the code in default_popup as early as onClicked.

This is the new popup script:

(async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  try {
    await chrome.scripting.executeScript({
      target: { tabId: tab.id, allFrames: true },

      files: ['script.js'],
    });
  } catch (erri) {
    console.error(`failed to execute script: ${erri}`);
  }
})();
  

Reply all
Reply to author
Forward
0 new messages