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...
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:
function getData() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
user_data = xmlhttp.responseText;
window.user_data = user_data;
processdata();
}
}
xmlhttp.open("GET","http://localhost:8888/g_dta.php",true);
xmlhttp.send();
}
getData();
function processdata() {
var downdata = user_data.split('|||||');
var installedthemes = downdata[0];
var currenttheme = downdata[1].toString();
window.currenttheme = currenttheme;
click();
}
function click(e) {
function setCSS() {
chrome.tabs.insertCSS(null, {file:currenttheme + ".css"});
}
setTimeout(function(){setCSS()}, 1250);
document.getElementById('iFrameLocation').innerHTML = "<iframe src='http://localhost:8888/wr_dta.php?newid="+e.target.id+"'></iframe>";
getData();
}
document.addEventListener('DOMContentLoaded', function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', click);
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With