我需要删除从 content_scripts (manifest.json) 注入(inject)的 CSS 文件 styles.css
"content_scripts": [{
"matches": ["*://*.youtube.com/*"],
"css": ["styles.css"],
"js": ["jquery-3.1.1.min.js", "content.js"]
}],
我想在我的扩展中做的一些解释。
首先 styles.css
被加载,它改变了页面上的一些代码。它有效。
然后,用户想要单击按钮并关闭扩展程序。它有效。
但是 styles.css
必须被删除。它不起作用。
有时用户想要打开扩展程序并且 styles.css
必须再次添加。
当我尝试这样解决时:
var style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = chrome.extension.getURL('myStyles.css');
(document.head||document.documentElement).appendChild(style);
效果不是很好,因为当扩展启动时,页面会闪烁几毫秒。
最佳答案
我查看并找到了解决此问题的方法。
list .json
manifest.json
"content_scripts": [{
"matches": ["*://*.youtube.com/*"],
"js": ["jquery-3.1.1.min.js", "content.js"],
"run_at" : "document_start" // It runs content.js first until page loads
}],
"web_accessible_resources": ["styles.css"] // It provides styles.css for use in content.js
和content.js
function loadCSS(file) {
var link = document.createElement("link");
link.href = chrome.extension.getURL('css/' + file + '.css');
link.id = file;
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("html")[0].appendChild(link);
}
function unloadCSS(file) {
var cssNode = document.getElementById(file);
cssNode && cssNode.parentNode.removeChild(cssNode);
}
content.js 只加载 html 标签中的 file.css(提供的 styles.css)直到页面加载
关于javascript - Chrome 扩展 : How to remove content script CSS after injection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40767137/