我可以使用内容脚本 js 文件以编程方式注入 CSS 文件吗? [英] Can I inject a CSS file programmatically using a content script js file?
问题描述
我可以使用内容脚本 js 文件以编程方式注入 CSS 文件吗?
Can I inject a CSS file programmatically using a content script js file?
当js文件链接到我的popup.html时,我可以注入css.问题是我必须单击按钮才能打开弹出窗口以注入 css.我希望它在后台自动发生.
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...
- 通过 XMLHttpRequest 从 MySQL 数据库中获取一个变量
- 调用函数processdata()"
- "processdata" 将处理来自 XMLHttpRequest 的数据.更具体地说,拆分变量,将其放入 2 个不同的变量并使它们成为全局变量
- 我调用函数click()"
- "click" 然后将在 1250 毫秒后使用 setTimeout 设置 css
- 我使用 chrome.tabs.insertCSS 来插入 css.css 名称是变量,currenttheme"
正如我之前提到的,它确实使用弹出窗口工作.但是必须在注入 CSS 之前打开弹出窗口.
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?
这是我的代码:
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);
}
});
推荐答案
您可以通过编程方式创建一个新的 标签并将其添加到
> 部分就像 JS 文件是动态加载的.
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);
这是一篇文章主题.
这篇关于我可以使用内容脚本 js 文件以编程方式注入 CSS 文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!