Chrome Extension: How to insert CSS conditioned on variable from Chrome storage using insert CSS?

Tags: , ,



I’m somewhat new to Chrome Extensions, so I think I may just be missing something small, but I’m trying to allow users to load an additional page of CSS and a page of JS depending on their options (it’s basically a different theme).

I’m storing the variable that should trigger the load as tm

Right now, in the JS page, I have:

var Theme;
function getVars() {
  chrome.storage.sync.get({
    tm: "",
  }, function(items) {
    Theme = items.tm;
    changeTheme();
  });
}

Which triggers the changeTheme function, and—depending on the value of Theme—runs the correct JS functions.

The trouble is that I also need a CSS sheet to load, but I can’t figure this part out. Right now, in that same JS file, in the changeTheme function, I’m also calling:

chrome.tabs.insertCSS({file: "starWars.css"});

This gives me the error:

 Error in response to storage.get: TypeError: Cannot read property 'insertCSS' of undefined
at changeTheme (chrome-extension://ipicalmjapbogbfpaddglpachiijdffn/starWars.js:96:14)
at Object.callback (chrome-extension://ipicalmjapbogbfpaddglpachiijdffn/starWars.js:7:5)
at getVars (chrome-extension://ipicalmjapbogbfpaddglpachiijdffn/starWars.js:3:23)
at chrome-extension://ipicalmjapbogbfpaddglpachiijdffn/starWars.js:10:1

My manifest version is 2, unlike the other StackOverflow posts I’ve found on this. You can’t use background in a version 2 manifest, and I need to stay in this version for other reasons. I do have "tabs" and "activeTab" in my permissions, as well as the page that the extension is for.

Can anyone point me in the right direction from here? Glad to provide more information if needed.

Answer

  1. You can use the background page/script with Manifest v2. The documentation says:

The background_page property has been replaced with a background property that contains either a scripts or page property. Details are available in the Event Pages documentation. 2. You can use chrome.tabs.insertCSS from a popup/background script 3. You can’t use chrome.tabs.insertCSS from a content script

So if you want to inject the CSS file inside your content script you have two options:

  1. send a message to the background script and insert the CSS file in the message listener

  2. declare the CSS file in manifest.json under “web_accessible_resources” key and simply add a <link> element that points to that CSS file:

     document.head.insertAdjacentHTML('beforeend',
         '<link rel="stylesheet" type="text/css" href="' + 
                chrome.runtime.getURL("starWars.css") + '">'
     );
    


Source: stackoverflow