Can I inject a CSS file programmatically using a content script js file?

你。 提交于 2019-11-28 05:26:39

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

var link = document.createElement("link");
link.href = "http://example.com/mystyle.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);

Here's an article on the topic.

Devin G Rhode

Extension flicker

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

Preface:

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

The gist

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

That code looks like this:

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

For some dynamic css code:

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

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

The reasoning

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

Parting words

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

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

 , "web_accessible_resources": [
        "mystyle.css"
    ]

and also add this 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 injection and insertCSS().

chrome.tabs.insertCSS(integer tabId, object details, function callback)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!