CSS Independent Content

From GreaseSpot Wiki
Revision as of 04:55, 3 June 2007 by Henrik (talk | contribs) (Now with working code :p)
Jump to navigationJump to search

Any HTML you inject into a site is subject to the CSS rules of that site. For many modifications, this is what you want: the elements you inject will fit in nicely. But if you inject something – perhaps a configuration panel – that should look the same across an entire site where styles can vary wildly (e.g. MySpace, eBay) or across multiple sites, you may find that you want it exempt from the site CSS.

The solution is to add your code inside an iframe. This is a bit tricky. Example code:

// position:fixed means it scrolls along with the page. The z-index is necessary on sites
// like Wikipedia and GreaseSpot. The border is just a border. The rest of the CSS centers 
// the iframe horizontally and vertically.
var css = 'position:fixed; top:50%; left:50%; width:30em; height:20em; margin-left:-15em;' + 
          'margin-top:-10em; border:1px solid #000; z-index:9999';

var iframe = document.createElement('iframe');
iframe.setAttribute('style', css);

// The about:blank page becomes a blank(!) canvas to modify
iframe.setAttribute('src', 'about:blank');


var iframeWindow = unsafeWindow.frames[unsafeWindow.frames.length-1];

// The timeout ensures this code is not run until Firefox has created the new DOM
setTimeout(function() {

    var doc = iframeWindow.document;
    doc.body.style.background = 'red';
    doc.body.innerHTML = 'Test.';

}, 0);