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…
- Get a variable from a MySQL database through a XMLHttpRequest
- Call the function, “processdata()”
- “processdata” Will process the data from the XMLHttpRequest. More specifically, split the variable, put it into 2 different variables and make them global
- I call the function, “click()”
- “click” Then will set the css after 1250 milliseconds using setTimeout
- 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
x
48
48
1
function getData() {
2
if (window.XMLHttpRequest)
3
{// code for IE7+, Firefox, Chrome, Opera, Safari
4
xmlhttp=new XMLHttpRequest();
5
}
6
else
7
{// code for IE6, IE5
8
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
9
}
10
xmlhttp.onreadystatechange=function()
11
{
12
if (xmlhttp.readyState==4 && xmlhttp.status==200)
13
{
14
user_data = xmlhttp.responseText;
15
window.user_data = user_data;
16
processdata();
17
}
18
}
19
xmlhttp.open("GET","http://localhost:8888/g_dta.php",true);
20
xmlhttp.send();
21
}
22
23
getData();
24
25
function processdata() {
26
var downdata = user_data.split('|||||');
27
var installedthemes = downdata[0];
28
var currenttheme = downdata[1].toString();
29
window.currenttheme = currenttheme;
30
click();
31
}
32
33
function click(e) {
34
function setCSS() {
35
chrome.tabs.insertCSS(null, {file:currenttheme + ".css"});
36
}
37
setTimeout(function(){setCSS()}, 1250);
38
document.getElementById('iFrameLocation').innerHTML = "<iframe src='http://localhost:8888/wr_dta.php?newid="+e.target.id+"'></iframe>";
39
getData();
40
}
41
42
document.addEventListener('DOMContentLoaded', function () {
43
var divs = document.querySelectorAll('div');
44
for (var i = 0; i < divs.length; i++) {
45
divs[i].addEventListener('click', click);
46
}
47
});
48
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
1
6
1
var link = document.createElement("link");
2
link.href = "http://example.com/mystyle.css";
3
link.type = "text/css";
4
link.rel = "stylesheet";
5
document.getElementsByTagName("head")[0].appendChild(link);
6
Here’s an article on the topic.