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

前端 未结 3 1604
感情败类
感情败类 2020-12-08 08:04

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

It is possible for me to inject the css when the js file is linked to my popup.html. The pro

相关标签:
3条回答
  • 2020-12-08 08:37

    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.

    0 讨论(0)
  • 2020-12-08 08:50

    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)
    
    0 讨论(0)
  • 2020-12-08 09:00

    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.
    0 讨论(0)
提交回复
热议问题