Alex Rivera | Logout

Prevent existing CSS from styling injected HTML/CSS

Asked 2009-04-09T04:07:35.250
18

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.

Edit
Report

1 Answer

0

If you're using a Mozilla browser you can actually (if illegally) add visible DOM content to the <html> element outside the <body> element. This will avoid any styles that match on body and are inherited by your content. It may be possible that some styles match on html, which would defeat this technique, but I've found it useful.

eg. using jquery: $('html').append('<div id="mycontent"> blah blah blah </div>');

Using a popular library is itself a challenge when you don't want your instance of the library to interfere with the uses of the library defined by the pages you're modifying. Greasemonkey's '@require' didn't work for me. I found it necessary (but possible!) to save any existing values of the two or three global names assigned by the jquery script, insert my instance of the library into the DOM, wait for it to be loaded (had to use a timer, that's annoying but I couldn't see a way around it), cache the values assigned to the globals within my own namespace for my own use, and restore the saved ones.

answered 2009-04-23T06:57:26.383

Your Answer