通过iframe脚本加载器避免全局变量的污染?

Dag*_*bit 7 javascript iframe global-variables

问题...

存在编码不良的脚本,需要包含在网页中.

这些脚本通过以下方式污染全局范围:

  • 将值分配给未声明的标识符
  • 向内置构造函数(如ObjectArray)及其原型添加属性
  • 其他讨厌的东西.

解?

我希望包含脚本而没有不良副作用.我认为可以通过在iframe中加载脚本并将对象导出为父窗口的属性来实现.这是我到目前为止所得到的:

<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>
Run Code Online (Sandbox Code Playgroud)

问题:

  • 如果脚本修改内置原型并将其移动到另一个窗口,或者我父窗口的内置插件是否保持干净并且所有内容都"正常工作?",是否会有潜在的破坏?

  • 这个想法是否适用于"大多数"浏览器,还是有一个显示阻止?到目前为止,还没有测试除chrome和moz之外的任何东西.

  • 我想在将对象拉入当前窗口后删除iframe,但如果iframe被删除,moz将丢失对象引用.有谁知道这方面的方法?

  • 这已经完成了,还是有更好的方法来实现我的目标?如果是这样,我应该寻找的脚本或技术的名称是什么?

(从这里移植的问题)

Ben*_*Ben 1

要复制函数,您可以将其转换为字符串,然后对其进行评估......下面的代码还演示了执行此操作后可以删除 iframe,并且您的副本保持不变。

以下代码示例使用 FF

Child.html 片段

<script>

//
// modify the prototype
//
Object.prototype.test = function(msg)
{
        alert(msg);
};  

//
// Simply declare a function
//
var whoo_hoo = function(){alert("whoo hoo");}
</script>
Run Code Online (Sandbox Code Playgroud)

带有 iframe 的父级:

 <iframe id="help_frame" src="http://localhost/child.html"
 onLoad="javascript:Help.import_functions(this)"></iframe>

    <script>
    var Help = {

          imported_function :null,
              import_functions : function(iframe)
   {
    this.imported_function = String(iframe.contentWindow.whoo_hoo);
    eval("this.imported_function = " + this.imported_function);
    iframe.parentNode.removeChild(iframe);

   //
   // displays 'whoo hoo' in an alert box
   //
   this.imported_function();

   try
   {
      //
      // If the Object prototype was changed in the parent
      // this would have displayed 'should not work' in an alert
      //
      this.test('should not work');
   }
   catch(e){alert('object prototype is unmodified');}

   }, 
    </script>
Run Code Online (Sandbox Code Playgroud)

http://thecodeabode.blogspot.com/