I am using bootstrap for a chrome extension I am writing. When imported as content script the css seem to clash with alot of the sites I am viewing (even in google search result page).
Wondering if there is anything i can do to scope this to just the dom elements I inject using content script?
The solution is to use <style scoped>
.
Essentially it allows you to apply a style to a DOM node and its children, but not its parent nodes. There's a nice article on CSS-Tricks explaining how to use it.
The problem is that it's not very well supported, even in Chrome, so you'll have to use a jQuery polyfill. This is basically a jQuery plugin that simulates the functionality you'd expect from <style scoped>
.
Here's a working JSFiddle doing exactly that using Bootstrap.
Here's an example of how you could implement it in your extension:
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
For now, make sure to include jQuery in your page, as well as the Scoped Plugin:
"content_scripts": [ {
"js": [ "jquery.min.js", "jquery.scoped.min.js", "content_script.js" ],
"matches": [ "http://*" ]
}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With