Chrome Extensions: CSS Injection on Manifest Version 3

Viewed 3082

I am attempting to inject CSS code into the active tab from a chrome extension, yet nothing I have looked at online so far has worked for me. I am fairly new to all of this, so apologies if my question is a bit naive and I am just missing something basic. Here is what I have come up with so far:

function inject_1(){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    css = 'body { background-color = "red" !important; }';
    chrome.scripting.insertCSS(
     {
       target: {tabId: tabs[0].id},
       css: css,
     }, function() {
       if (chrome.runtime.lastError) {
         message.innerText = 'There was an error injecting css : \n' + chrome.runtime.lastError.message;
       }
     });
  });
}

Here is a secondary method I tried:

function inject_2(){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.scripting.executeScript(
     {
       target: {tabId: tabs[0].id},
       files: ["inject.css"],
     }, function() {
       if (chrome.runtime.lastError) {
         message.innerText = 'There was an error injecting css : \n' + chrome.runtime.lastError.message;
       }
     });
  });
}

Neither function returns an error message, but they also don't change the webpage at all. I would greatly appreciate any help with this (rework of my code or something completely new to try). Thanks.

2 Answers

Bit late, but I got this working for a personal project; maybe try something to the effect of:

...
    chrome.scripting.insertCSS({
        target: { tabId: tabs.id },
        files: ["inject.css"]
    });
...

You can specify files for insertCSS as you've done for executeScript in your secondary method.

I would just add a .css file to the extension.

style.css

body {
  background-color: red !important;
}

and then added it to the content_scripts in manifest.json e.g.

...
"content_scripts": [
  {
    ...,
    "css": ["style.css"]
  }

I'm also not sure if your 'body { background-color = "red" !important; }' shouldn't be 'body { background-color:red !important; }'

Related