2016-11-23 119 views
2

我需要删除从content_scripts(manifest.json中)注入的CSS文件styles.cssChrome扩展程序:如何删除注入后的内容脚本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); 

它没有很好地工作,因为当扩展入门然后页面会在几毫秒内闪烁。

+0

问题已关闭。我很沮丧。谢谢。 – Lestoroer

+0

“问题已关闭”是否意味着您不再在意这个主题,因为您不再在意(除了您找到解决方案之外的其他原因),还是您找到了问题的解决方案或其他内容?如果你发现问题的解决方案,那么你应该回答这个问题。 [鼓励自我回答的问题](http://stackoverflow.com/help/self-answer)。 – Makyen

+0

所以。是。我稍后再介绍解决方案:) – Lestoroer

回答

2

我看了一下,发现了这个问题的解决方案。

的manifest.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仅加载file.css(styles.css的将其提供),以html标签直到页面加载

+0

所以“不建议像X这样的代码”和你的代码之间唯一真正的区别是'run_at'? – Xan

+1

是的。起初,我用''run_at':“document_end”'(这是默认值)运行代码并发生闪烁。然后我发现了''run_at':'document_start'',并且所有的作品都很好。只是我不知道我最近遇到了谷歌API。 – Lestoroer

+0

我更新了这个问题,以更好地反映这一点,我将upvote你的答案。 – Xan

相关问题