频道栏目
首页 > 资讯 > HTML/CSS > 正文

window.name+iframe实现跨域

17-06-29        来源:[db:作者]  
收藏   我要投稿

window.name属性有这样的特点:
当前页设置的值, 在页面重新加载(非同域也可以)后, 值依然不变.
比如:

window.name = 'abc';
window.name; // abc
window.location = 'http://www.baidu.com';
window.name; // abc

利用这个加上iframe就可以实现跨域数据传递.
iframe会创建一个 新的窗口(也就是一个 干净的环境), 也有name属性.

下面来实验下:

├── one/
│   ├── a.html
│   └── proxy.html
└── two/
    └── b.html

利用http-server来模拟跨域的情况:

cd one/
screen -S one http-server -p 8001
cd ../two/
screen -S two http-server -p 8002
google-chrome http://localhost:8001/a.html

注意上述用了端口不同来制造非同源的情况.
其中页面主要代码如下:
proxy.html是一个空白页面, 主要是为了和a.html通信用.

b.html提供数据用:

<script>
    window.name = 'b.html\'s data';
</script>

a.html

<script type="text/javascript">
var otherLoaded = false,
iframe = document.createElement('iframe'),
loadfn = function() {
    if (otherLoaded) {
        var data = iframe.contentWindow.name; // 读取数据
        alert(data); // 弹出b.html's data

        // 清理工作
        iframe.contentWindow.document.write('');
        iframe.contentWindow.close();
        document.body.removeChild(iframe);
    } else if (!otherLoaded) {
        otherLoaded = true;
        iframe.contentWindow.location = "http://localhost:8001/proxy.html"; // 设置的代理文件
    }
};
iframe.src = 'http://localhost:8002/b.html';
if (iframe.attachEvent) {
    iframe.attachEvent('onload', loadfn);
} else {
    iframe.onload = loadfn;
}
document.body.appendChild(iframe);
</script>

可以看到, 第一次设置iframe的地址为b.html, 这样的话b.html会被加载进来,
但是并不能直接访问iframe.contentWindow.name, 因为a.html和b.html目前不同源,
如果将loadfn的实现改为var data = iframe.contentWindow.name;,会出来这个错误:

a.html:14 Uncaught DOMException: Blocked a frame with origin "http://localhost:8001" from accessing a cross-origin frame.

那怎么办呢, 既然不同源, 就改成同源呗, 所以将iframe地址改成与a.html同源的proxy.html,
由于window.name在地址变化时值不变, 所以iframe.contentWindow.name的值还是之前的值, 也就是b.html窗口的值, 而又满足的同源的要求, 所以可以访问成功.

参考:
http://www.tuicool.com/articles/viMFbqV

欢迎补充指正!

相关TAG标签
上一篇:CSS3学习
下一篇:Play+scala上传文件教程
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站