[ACCEPTED]-Can I inject a CSS file programmatically using a content script js file?-google-chrome-devtools

Accepted answer
Score: 74

You can programmatically create a new <link> tag 3 and add it to the <head> section just like JS 2 files are loaded dynamically.

var link = document.createElement("link");
link.href = "http://example.com/mystyle.css";
link.type = "text/css";
link.rel = "stylesheet";

Here's an article on 1 the topic.

Score: 12

Extension flicker

A trauma to the ecosystem that isn't hard to fix


Among 17 many ways to get your css added to a page, most 16 of them cause the screen to flicker - initially 15 showing the page without your css applied, and 14 then later applying it. I've tried several 13 ways, below are my findings.

The gist

You need to 12 append a CSS <link> or a <style> tag in a Content script injected on document_start

That code looks 11 like this:

var link = document.createElement('link');
link.href =  chrome.runtime.getURL('main.css');
  //chrome-extension://<extension id>/main.css
link.rel = 'stylesheet';

For some dynamic CSS code:

var customStyles = document.createElement('style'); 
   'body { background-color: ' + localStorage.getItem('background-color') + '}'

Doing 10 this in a script on document_start ensures there is no flicker!

The reasoning

In 9 this JavaScript file you can handle any 8 number of programmatic things. The URL pattern 7 matching offered in manifest.json is very limited, but 6 here you can actually look at all the ?query_string and 5 #hash of a url, and use full regular expressions 4 and string operations to decide whether 3 or not to inject CSS. That CSS can also 2 be based on settings, and/or coordinate 1 with messaging to the background page.

Parting words

  • Don't use .insertCSS, you will notice a flicker.
Score: 1

It's to simple you could add to the manifest's 3 permissions field : See web_accessible_resources

 , "web_accessible_resources": [

and also add this 2 in content_scripts

"content_scripts": [
        "matches": ["<all_urls>"],
        "css": ["mystyle.css"],
        "js": ["jquery-1.10.2.min.js","content.js","my.min.js"]

you also add same thing using Programmatic 1 injection and insertCSS().

chrome.tabs.insertCSS(integer tabId, object details, function callback)

More Related questions