在父窗体中,要把执行环境切换到iframe内部,使用 new Function,事件,Event等都会无效,执行环境始终会在父窗口中。
要切换环境需要把要执行的函数写到iframe内部的script标签:
var doc = iframe.contentWindow.document;
var head, headtag = doc.getElementsByTagName('head');
if (headtag.length) {
head = headtag[0];
}
else {
head = doc.createElement('head');
doc.appendChild(head);
}
var script = doc.createElement("script");
script.type = "text/javascript";
script.cpjsremovable = 12345655;//动态创建标签标记
try {
script.appendChild(new doc.createTextNode(jsContent));
} catch (e) { script.text = jsContent; }
head.appendChild(script);
jsContent是要执行的JS内容,可以用 Function.toString()获得。
参数传递可以用 document,window,topwindow等对象附加属性来传递
//=====传说中的分割线===================================
经过进一步的测试,JS的function拥有类似dom.ownerDocument的属性,在执行该函数时,会自动切换到创建该函数的doucment环境。
所以切换环境,不是切换执行环境,而是要切换函数的创建环境。
调试过程中,没找到公开的 Function.ownerDocument属性,所以不能通过代码修改来切换环境,只能通过函数的创建环境来完成目标。