Updated:

I made some big progress on running the content script on its designated pages! 🥰

I was struggling with the chrome.scripting.executeScript method, since most examples online were based on manifest v2, which uses chrome.tabs.executeScript.

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
    const regex = /https:\/\/band.us\/band\/[0-9]{8}\/member/gm
    const isBand = tabs[0].url.match(regex);
    if (!isBand) {
      $('#alertNotOnBand').show();
      $('#onBand').hide();
    } else {
      $('#onBand').show();
      $('#alertNotOnBand').hide();

      // Execute content script
      const tabId = tabs[0].id;
      chrome.scripting.executeScript(
        {
          target: {tabId},
          files: ['content-script.js'],
        }, () => {
          console.log("content script executed");
        });
    }
});

The code above hides and shows <div> elements using jQuery, and only runs content-script.js when the tab is open at members page of band.us.

Another reason I struggled was because of the permissions in manifest.json. Apparently with manifest v3, host permissions should be declared separately as shown below.

{
  "permissions": [
    "storage",
    "tabs",
    "scripting",
    "declarativeContent"
  ],
  "host_permissions": [
    "*://band.us/band/*"
  ]
}

Now I should work on using the storage API to communicate between the background JavaScript and the content script!

Tags:

Categories:

Updated:

Leave a comment