CSS Independent Content: Difference between revisions
From GreaseSpot Wiki
Jump to navigationJump to search
Now with working code :p |
Alien scum (talk | contribs) removed unnecessary unsafeWindow |
||
Line 16: | Line 16: | ||
document.body.appendChild(iframe); | document.body.appendChild(iframe); | ||
// The timeout ensures this code is not run until Firefox has created the new DOM | // The timeout ensures this code is not run until Firefox has created the new DOM | ||
setTimeout(function() { | setTimeout(function() { | ||
var doc = | var doc = iframe.contentDocument; | ||
doc.body.style.background = 'red'; | doc.body.style.background = 'red'; | ||
doc.body.innerHTML = 'Test.'; | doc.body.innerHTML = 'Test.'; | ||
}, 0); | }, 0); |
Revision as of 18:40, 4 June 2007
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'); document.body.appendChild(iframe); // The timeout ensures this code is not run until Firefox has created the new DOM setTimeout(function() { var doc = iframe.contentDocument; doc.body.style.background = 'red'; doc.body.innerHTML = 'Test.'; }, 0);