google-chrome - 在 chrome 扩展中,twitter bootstrap css 发生冲突

标签 google-chrome google-chrome-extension twitter-bootstrap

我正在将 Bootstrap 用于我正在编写的 chrome 扩展。当作为内容脚本导入时,css 似乎与我正在查看的许多网站发生冲突(即使在谷歌搜索结果页面中)。

想知道我是否可以做些什么来将其范围仅限于我使用内容脚本注入(inject)的 dom 元素?

最佳答案

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

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

问题是它没有得到很好的支持,即使在 Chrome 中也是如此,所以你必须使用 jQuery polyfill。这基本上是一个 jQuery 插件,可以模拟您期望 <style scoped> 提供的功能。 .

这是一个有效的JSFiddle使用 Bootstrap 就可以做到这一点。

这是一个如何在扩展中实现它的示例:

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

现在,请确保在您的页面中包含 jQuery 以及 Scoped Plugin:
"content_scripts": [ {
    "js": [ "jquery.min.js", "jquery.scoped.min.js", "content_script.js" ],
    "matches": [ "http://*" ]
}]

关于google-chrome - 在 chrome 扩展中,twitter bootstrap css 发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123044/

相关文章:

javascript - 什么是 "DOMException: Entry already exists"?

javascript - 触发 chrome.browserAction.onClicked.addListener 时出现问题

javascript - 在 chrome 扩展程序中打开 url 而不打开选项卡?

twitter-bootstrap - 您如何仅在移动 View 中将一个元素放在另一个元素之上?

css - 对齐工具栏中的元素

javascript - 如果值在变量中,Firefox 和 IE 不会调用 window.location.href

google-chrome - 使用XHR轮询时如何解决Chrome的6个连接限制

google-chrome - 将变量从后台传递到 Chrome 扩展程序上的弹出窗口

javascript - Chrome 扩展 - 使用 javascript 定期运行并永久记录数据

twitter-bootstrap - Bootstrap 图标不显示