简体   繁体   English

如何在chrome扩展内容脚本中定位CSS

[英]How to scope CSS in chrome extension content scripts

I am developing a chrome extension that injects a button onto a page. 我正在开发一个chrome扩展,它在页面上注入一个按钮。 When this button is clicked, it launches a twitter bootstrap modal. 单击此按钮时,将启动twitter bootstrap模式。 However, the css that is injected with the twitter bootstrap is affecting the pages themselves and I only want them to affect the modal divs. 但是,使用twitter bootstrap注入的css会影响页面本身,我只希望它们影响模态div。 How can I achieve this? 我怎样才能做到这一点?

Thank you! 谢谢!

There is only one true way to do that and it involves LESS 只有一种真正的方法可以做到这一点而且它涉及的很少

See this answer: https://stackoverflow.com/a/14145510/1060487 请参阅此答案: https//stackoverflow.com/a/14145510/1060487

Or this one: https://stackoverflow.com/a/15115171/1060487 或者这个: https//stackoverflow.com/a/15115171/1060487

Both approaches should work fine. 这两种方法都应该可行。

I've experimented with 1 other solution: 我已经尝试了另外一个解决方案:

http://css-tricks.com/saving-the-day-with-scoped-css/ http://css-tricks.com/saving-the-day-with-scoped-css/

Which DOES NOT work in Chrome but there is a polyfill here , which doesn't really seem to work that well... 哪个在Chrome中不起作用,但这里有一个polyfill ,这似乎并没有那么好......

Check the support here: http://caniuse.com/style-scoped 查看支持点: http//caniuse.com/style-scoped

Summary : the LESS route seems to be the best solution right now... 总结 :LESS路线似乎是目前最好的解决方案......

I recently created Boundary, a CSS+JS library to solve problems just like this. 我最近创建了Boundary,一个CSS + JS库来解决这样的问题。 Boundary creates elements that are completely separate from the existing webpage's CSS. 边界创建的元素与现有网页的CSS完全分开。

Take creating a dialog for example. 以创建对话框为例。 After installing Boundary, you can do this in your content script 安装Boundary后,您可以在内容脚本中执行此操作

var dialog = Boundary.createBox("yourDialogID", "yourDialogClassName");

Boundary.loadBoxCSS("#yourDialogID", "style-for-elems-in-dialog.css");

Boundary.appendToBox(
    "#yourDialogID",
    "<button id='submit_button'>submit</button>"
);

Boundary.find("#submit_button").click(function() {
  // find() function returns a regular jQuery DOM element
  // so you can do whatever you want with it.
  // some js after button is clicked.
});

Elements within #yourDialogID will not be affected by the existing webpage. #yourDialogID中的元素不受现有网页的影响。

Hope this helps. 希望这可以帮助。 Please let me know if you have any question. 如果您有任何疑问,请告诉我。

https://github.com/liviavinci/Boundary https://github.com/liviavinci/Boundary

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM