问题…
存在编码不良的脚本,需要包含在网页中.
这些脚本通过以下方式污染全局范围:
>为未声明的标识符分配值
>向内置构造函数(如Object和Array)及其原型添加属性
>其他令人讨厌的东西.
解?
我希望包含脚本而不会产生不良副作用.我认为可以通过在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>
问题:
>如果脚本修改内置原型并将其移动到另一个窗口,或者我父窗口的内置插件是否保持干净并且一切都“正常工作”,是否会有潜在的破坏?
>这个想法是否适用于“大多数”浏览器,还是有一个显示阻止?到目前为止,还没有测试除chrome和moz之外的任何东西.
>我想在将对象拉入当前窗口后删除iframe,但如果iframe被删除,moz将丢失对象引用.有谁知道这方面的方法?
>这已经完成,还是有更好的方法来实现我的目标?如果是这样,我应该寻找的脚本或技术的名称是什么?
(移植自here的问题)
解决方法
要复制一个函数,你可以将它转换为一个字符串,然后评估它….下面的代码还演示了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>
使用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>