Kunal Tanwar
Kunal Tanwar

Reputation: 1291

Injecting custom CSS with content.js [CHROME EXTENSION] is not working

I created a chrome extension for changing default font of some websites.

manifest.json

{
  "name": "Custom Font",
  "version": "0.0.1",
  "description": "A Extension to change default Fonts.",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["https://dev.to/*", "https://github.com/*"],
      "js": ["main.js"] // content.js
    }
  ]
}

main.js

const head = document.head || document.getElementsByTagName('head')[0];

const link = document.createElement('link');
link.rel = 'stylesheet';

if (window.location.href.includes('https://dev.to')) {
  link.href = chrome.runtime.getURL('devTo.css');
}
if (window.location.href.includes('https://github.com')) {
  link.href = chrome.runtime.getURL('github.css');
}

head.appendChild(link);

but when I try to run above code in mentioned websites it is giving me an error :

GET chrome-extension://invalid/ net::ERR_FAILED

Upvotes: 1

Views: 2038

Answers (1)

user1731468
user1731468

Reputation: 1000

If you want to add the style dynamically from your JavaScript content script (in your Chrome extension manifest v3). You can do it like this:

Adding the stylesheet dynamically is a good idea, if you want to give the user an option to enable/disable it at any time. For example with an options page.

manifest.json

{
    "name": "Inject Style",
    "action": {},
    "manifest_version": 3,
    "version": "0.1",
    "description": "Inject the stylesheet from content script",
    "content_scripts": [
        {
            "matches": ["https://dev.to/*", "https://github.com/*"],
            "js": ["main.js"]
        }
    ],
    "permissions": ["activeTab"],
    "host_permissions": ["<all_urls>"],
    "web_accessible_resources": [
        {
            "resources": [ "devTo.css"],
            "matches": [ "https://dev.to/*" ]
        },
        {
            "resources": [ "github.css"],
            "matches": [ "https://github.com/*" ]
        }
    ]
}

main.js (content script)

function addstylesheet(filename){
    var link = document.createElement("link");
    link.href = chrome.runtime.getURL(filename);
    link.type = "text/css";
    link.rel = "stylesheet";
    document.getElementsByTagName("head")[0].appendChild(link);
}
    
if(window.location.href.match(/(https:\/\/(.*github\.com\/.*))/i)) {
    addstylesheet("github.css");
} else if(window.location.href.match(/(https:\/\/(.*dev\.to\/.*))/i) {
    addstylesheet("devTo.css");
}

Upvotes: 4

Related Questions