Search code examples
javascriptcssgoogle-chrome-extensionscriptingchrome-extension-manifest-v3

Execute Content Script and associated CSS from Background (Manifest V3) - Chrome Extension


I am coding a chrome extension, and I basically want that when it's active, a little circle displays on the screen. I NEED CSS for that, so what I'm trying to do is have the background in my manifest, and basically just execute the content script if the icon is clicked. Currently I know the setting is on if the tab url is changed, but I'm testing something out. I need to add the CSS to my content script, but not sure how to. I looked it up, and I saw insertCSS() was a thing, but that is only for a single line of code, I have much more than that. Any ideas please? I've reviewed the main google doc for it, and MDN as well. Any help would be appreciated.

//BACKGROUND

try {
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        if(changeInfo.status == 'complete') {
            chrome.scripting.executeScript({
                files: ['content-script.js'],
                target: {tabId: tab.id}
            });
        }
    });
} catch (e) {
    console.log(e);
}

//CONTENT-SCRIPT (in another file, wasn't sure how to add it to the question


if (typeof init === 'undefined') {
    const init = function() {
        const injectElement = document.createElement("button");
        injectElement.className = 'button_attempt';
        injectElement.innerHTML = "T";
        document.body.appendChild(injectElement);

    }

    init();
        
}
//CSS


@import url('https://fonts.googleapis.com/css2?family=Prociono&family=Sorts+Mill+Goudy&display=swap');

@font-face {
    font-family: 'Goudy Bookletter 1911';
    font-style: normal;
    font-weight: 400;
    src: url(https://fonts.gstatic.com/s/goudybookletter1911/v13/sykt-z54laciWfKv-kX8krex0jDiD2HbY6IJshzW.woff2) format('woff2');
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212,  U+2215, U+FEFF, U+FFFD;
}


.button_attempt {
      background-image: url(icon.png);
      width: 2.5rem;
      height: 2.5rem;
      font-family: 'Goudy Bookletter 1911';
      font-size: 1.25rem;
      color: white;
      background-color: #A485C7;
      cursor: pointer;
      border: 2px solid #D0B3F1;
      border-radius: 50%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 10;
      /*display: none;*/

      transition: color 0.2s, background-color 0.2s ease-in-out;
}

.button_attempt:hover {
      color: #A485C7;
      background-color: white;
}
//MANIFEST
{

"name" : "Practice",
"version" : "1.0.0",
"manifest_version" : 3,
"background" : {
    "service_worker": "background.js"
},

"permissions" : ["scripting"],

"host_permissions": ["<all_urls>"]

}


Solution

  • It's pretty simple :)

    1. Change the manifest file to something like this.

    manifest.json:

    {
    
    "name" : "Practice",
    "version" : "1.0.0",
    "manifest_version" : 3,
    "background" : {
        "service_worker": "background.js"
    },
    
    "permissions" : ["scripting"],
    
    "host_permissions": ["<all_urls>"]
    "content_scripts": [
        {
          "matches": ["http://*/*", "https://*/*"],
          "css": ["content_style.css"],
          "js": ["content_script.js"],
          "run_at": "document_end"
        }
      ],
    
    }
    
    1. Invoke the content_script.js from background.js. You can whatever kind of listener for this.

    background.js:

    chrome.tabs.onUpdated.addListener(function () {
      chrome.tabs.executeScript(null, { file: "content_script.js" });
    });
    
    1. Use the content_script.js to do changes to the DOM. You can add style classes to DOM nodes which is applied from the content_style.css or add new elements like the ones you want. Write all your new CSS rules in content_style.css.