Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twitter bootstrap css clashes while in chrome extensions

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?

like image 809
charleetm Avatar asked Oct 29 '12 13:10

charleetm


1 Answers

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://*" ]
}]
like image 193
Talmo Pereira Avatar answered Jan 01 '23 10:01

Talmo Pereira