window.name + iframe 实现跨域

来源:互联网 发布:族谱制作软件 编辑:程序博客网 时间:2024/06/07 22:45

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

window.name = 'abc';window.name; // abcwindow.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 8001cd ../two/screen -S two http-server -p 8002google-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

欢迎补充指正!