在boot扩展中的twitter bootstrap css冲突

cha*_*etm 5 google-chrome google-chrome-extension twitter-bootstrap

我正在使用bootstrap作为我正在编写的chrome扩展.当作为内容脚本导入时,css似乎与我正在查看的很多站点冲突(即使在谷歌搜索结果页面中).

想知道我是否可以做任何事情来限制我使用内容脚本注入的dom元素?

小智 13

解决方案是使用<style scoped>.

本质上,它允许您将样式应用于DOM节点及其子节点,但不应用于其父节点.关于CSS-Tricks的一篇很好的文章解释了如何使用它.

问题是,即使在Chrome中,它也不是很受支持,所以你必须使用jQuery polyfill.这基本上是一个jQuery插件,可以模拟您期望的功能<style scoped>.

这是一个正在使用Bootstrap的JSFiddle.

以下是您可以在扩展程序中实现它的示例:

content_script.js:

$.scoped(); // Initialize the plugin
...
bootstrapped = document.createElement("div");
bootstrapped.innerHTML = "<style scoped>";
bootstrapped.innerHTML += "@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');";
bootstrapped.innerHTML += "</style>";
document.body.appendChild(bootstrapped);    
...
document.body.appendChild(myDOM); // Will not possess Bootstrap styles
bootstrapped.appendChild(myDOM); // Will possess Bootstrap styles
Run Code Online (Sandbox Code Playgroud)

现在,请确保在您的页面中包含jQuery,以及Scoped插件:

"content_scripts": [ {
    "js": [ "jquery.min.js", "jquery.scoped.min.js", "content_script.js" ],
    "matches": [ "http://*" ]
}]
Run Code Online (Sandbox Code Playgroud)