Problem...
Poorly-coded scripts exist which need to be included on a web page.
These scripts pollute the global scope by doing things like:
- Assigning values to undeclared identifiers
- Adding properties to built-in constructor functions (like
Object
andArray
) and their prototypes - Other nasty stuff.
Solution?
I want to include the scripts without the adverse side effects. I think it can be achieved by loading the script in an iframe and exporting objects as properties of the parent window. Here's what Ive got so far:
<script>
(function(){
var g=this, frameIndex=frames.length, f=document.createElement('iframe');
// hide it like this instead of display:none, because some old browser ignores
// iframes with display:none, or is this an ancient habit I can drop?
f.style.width='0px'; f.style.height='0px';
f.style.border='none'; f.style.position='absolute';
// append it to document.body or document.documentElement?
// documentElement seems to work before body is loaded,
// but is it cross-browser safe?
document.body.appendChild(f);
// window object for our iframe
var w=frames[frameIndex];
// callback function pulls the object into the current window when script loads
w.cb=function(){ g.SomeObject=w.SomeObject };
// will this work on IE, or do I need to use document.createElement?
// wanted to avoid document.createElement in this case because I'm not sure
// whether to call it from window.document or frames[frameIndex].document
w.document.innerHTML='<script onload="cb()" src="myscript.js"><\/script>';
}());
</script>
Questions:
Will there be potential havoc if a script modifies built-in prototypes and I move it into another window, or will my parent window's built-ins stay clean and everything will "just work?"
Is this idea going to work on 'most' browsers, or is there a show-stopper? Haven't tested on anything besides chrome and moz so far.
I'd like to remove the iframe after pulling the object into the current window, but moz will lose the object reference if the iframe is removed. Does anyone know of a way around that?
Has this already been done, or is there a better way to accomplish my goal? If so, what's the name of the script or technique I should to be looking for?
(question transplanted from here)