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

前端之家收集整理的这篇文章主要介绍了javascript – 通过iframe脚本加载器避免全局变量的污染?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题…

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

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

>为未声明的标识符分配值
>向内置构造函数(如Object和Array)及其原型添加属性
>其他令人讨厌的东西.

解?

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

  1. <script>
  2.  
  3. (function(){
  4. var g=this,frameIndex=frames.length,f=document.createElement('iframe');
  5.  
  6. // hide it like this instead of display:none,because some old browser ignores
  7. // iframes with display:none,or is this an ancient habit I can drop?
  8. f.style.width='0px'; f.style.height='0px';
  9. f.style.border='none'; f.style.position='absolute';
  10.  
  11. // append it to document.body or document.documentElement?
  12. // documentElement seems to work before body is loaded,// but is it cross-browser safe?
  13. document.body.appendChild(f);
  14.  
  15. // window object for our iframe
  16. var w=frames[frameIndex];
  17.  
  18. // callback function pulls the object into the current window when script loads
  19. w.cb=function(){ g.SomeObject=w.SomeObject };
  20.  
  21. // will this work on IE,or do I need to use document.createElement?
  22. // wanted to avoid document.createElement in this case because I'm not sure
  23. // whether to call it from window.document or frames[frameIndex].document
  24. w.document.innerHTML='<script onload="cb()" src="myscript.js"><\/script>';
  25.  
  26. }());
  27.  
  28. </script>

问题:

>如果脚本修改内置原型并将其移动到另一个窗口,或者我父窗口的内置插件是否保持干净并且一切都“正常工作”,是否会有潜在的破坏?
>这个想法是否适用于“大多数”浏览器,还是有一个显示阻止?到目前为止,还没有测试除chrome和moz之外的任何东西.
>我想在将对象拉入当前窗口后删除iframe,但如果iframe被删除,moz将丢失对象引用.有谁知道这方面的方法
>这已经完成,还是有更好的方法来实现我的目标?如果是这样,我应该寻找的脚本或技术的名称是什么?

(移植自here的问题)

解决方法

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

以下代码示例使用FF

Child.HTML代码

  1. <script>
  2.  
  3. //
  4. // modify the prototype
  5. //
  6. Object.prototype.test = function(msg)
  7. {
  8. alert(msg);
  9. };
  10.  
  11. //
  12. // Simply declare a function
  13. //
  14. var whoo_hoo = function(){alert("whoo hoo");}
  15. </script>

使用iframe的父级:

  1. <iframe id="help_frame" src="http://localhost/child.html"
  2. onLoad="javascript:Help.import_functions(this)"></iframe>
  3.  
  4. <script>
  5. var Help = {
  6.  
  7. imported_function :null,import_functions : function(iframe)
  8. {
  9. this.imported_function = String(iframe.contentWindow.whoo_hoo);
  10. eval("this.imported_function = " + this.imported_function);
  11. iframe.parentNode.removeChild(iframe);
  12.  
  13. //
  14. // displays 'whoo hoo' in an alert Box
  15. //
  16. this.imported_function();
  17.  
  18. try
  19. {
  20. //
  21. // If the Object prototype was changed in the parent
  22. // this would have displayed 'should not work' in an alert
  23. //
  24. this.test('should not work');
  25. }
  26. catch(e){alert('object prototype is unmodified');}
  27.  
  28. },</script>

http://thecodeabode.blogspot.com/

猜你在找的JavaScript相关文章