Skip to content
Advertisement

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

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 problem is I have to click on the button to open the popup to inject the css. I want it to happen automatically and in the background.

What happens in my code…

  1. Get a variable from a MySQL database through a XMLHttpRequest
  2. Call the function, “processdata()”
  3. “processdata” Will process the data from the XMLHttpRequest. More specifically, split the variable, put it into 2 different variables and make them global
  4. I call the function, “click()”
  5. “click” Then will set the css after 1250 milliseconds using setTimeout
  6. I use chrome.tabs.insertCSS to insert the css. The css name is the variable, “currenttheme

As I mentioned before it does work using the popup. But the popup has to be opened before the CSS gets injected.

How do I make this all happen automatically, without any user interaction?

Here is my code:

JavaScript

Advertisement

Answer

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

JavaScript

Here’s an article on the topic.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement