Prevent existing CSS from styling injected HTML/CSS

Tom Corelis picture Tom Corelis · Apr 9, 2009 · Viewed 10.1k times · Source

I'm working on a project which injects JS+CSS+HTML over web pages which I do not have control over.

I am concerned about the host page styling my injected code -- I want my injected code to only obey my styling, and not theirs.

At the moment the only method to do this I can think of involves explicitly specifying every possible tag for the container <div>'s class (using pre-defined, known browser defaults) and relying on inheritance for those rules to propagate down to the rest of my injected HTML. This CSS would need to appear at the bottom of the page's <head> tag.

I don't think that's the best solution, though, and I don't look forward to implementing it. Surely there are better ways.

Answer

Dan Lew picture Dan Lew · Apr 9, 2009

Others have suggested very good ways to prevent your CSS from affecting the page's, as well as making sure that your CSS takes precedence, but you seem most concerned with the page's CSS affecting you - that is, adding a funky, unexpected style (like making all divs have a pink background).

The only way I can think for you to prevent their styling from affecting your injected code would be for you to sandbox what you've injected, like in an iframe. Otherwise there's simply too many things that you'd have to define - you'd have to define every single style (padding, border, margin, background... the list goes on and on) on the "*" selector (or better yet, "#yourid *", so you just override your own content), just so that you can guarantee absolute control over your CSS.

Edit: I realize that the latter solution wouldn't necessarily be too painful, if you're using the omni-selector to reset everything to a baseline:

#myid * {
    somestyle1: default;
    somestyle2: default;
    ... 
}

I've found someone who has written up such a solution. If you scroll down far enough on the page, you'll see it (from SuzyUK). It doesn't look complete, but is a good start for sure.

(I, too, would be interested to know if there's a good way to prevent this. I've written Greasemonkey scripts before that injects code onto the page, and have had to write CSS to override the page's CSS, but in those cases I knew who my target was and could tailor my CSS directly towards the page.)