利用window.name 实现iframe 跨域传值

原理:浏览器跨域ifram禁止互相调用/传值.但是调用iframe时 window.name 却不变,正是利用这个特性来互相传值,当然跨域下是不容许读取ifram的window.name值.所以这里我们还要准备一个和主页面http://www.a.com/main.html 相同域下的代理页面http://www.a.com/other.html ,iframe调用子页面 http://www.b.com/iframe.aspx

执行流程:

浏览器执行主页面 http://www.a.com/main.html 时创建iframe 加载子页面 http://www.b.com/iframe.aspx?nid=1000 子页面将要传递的值赋给window.name 后,这时有个变量开关 state=0,当 state等于0时,iframe 再加载代理页面 http://www.a.com/other.html (为什么加载这个,就是为了同域下 获取iframe 的window.name 值),下一步就是获取window.name 值,实现了跨域传值.

A页面(主页面 http://www.a.com/main.html)

代理页面(http://www.a.com/other.html)

B页面(iframe 调用的子页面 http://www.b.com/iframe.aspx)

 B页面把页面ID为 pop 元素的值赋给 window.name  代码如下:

 var p = document.getElementByIdx_x_x(“pop”).value;

window.name = p;

}

<script type=”text/javascript”>
//背弹广告
var iframeDate;
var state = 0,//开关变量
 iframe = document_createElement_x_x(‘iframe’),//创建iframe
loadfn = function() {
if (state === 1) {
iframeDate = iframe.contentWindow.name; // 读取数据
 if (iframeDate > 0) {
alert(“获取到了iframe出过来的值”);
}} else if (state === 0) {
state = 1;
 iframe.contentWindow.location = “http://www.a.com/other.html”; // 设置的代理文件,当走到这一步时,由于iframe的location改变了,导致重新执行 loadfn 方法(红色部分) 这时开关变量 state已经变为1 所以轻松获取window.name 的值.
}
};
 iframe.src = ‘http://www.b.com/ifram.aspx?nid=1000′;
if (iframe.attachEvent) {
iframe.attachEvent(‘onload’, loadfn);
} else {
iframe.onload = loadfn;
}
document.body.a(iframe);
</script>


回到顶部