window.name实现的跨域数据传输

这篇文章是对 JavaScript跨域总结与解决办法 的补充。javascript

有三个页面:html

  • a.com/app.html:应用页面。java

  • a.com/proxy.html:代理文件,通常是一个没有任何内容的html文件,须要和应用页面在同一域下。json

  • b.com/data.html:应用页面须要获取数据的页面,可称为数据页面。跨域

实现起来基本步骤以下:浏览器

  1. 在应用页面(a.com/app.html)中建立一个iframe,把其src指向数据页面(b.com/data.html)。
    数据页面会把数据附加到这个iframe的window.name上,data.html代码以下:安全

    <script type="text/javascript">
        window.name = 'I was there!';    // 这里是要传输的数据,大小通常为2M,IE和firefox下能够大至32M左右
                                         // 数据格式能够自定义,如json、字符串
    </script>
  2. 在应用页面(a.com/app.html)中监听iframe的onload事件,在此事件中设置这个iframe的src指向本地域的代理文件(代理文件和应用页面在同一域下,因此能够相互通讯)。app.html部分代码以下:cookie

    <script type="text/javascript">
        var state = 0, 
        iframe = document.createElement('iframe'),
        loadfn = function() {
            if (state === 1) {
                var data = iframe.contentWindow.name;    // 读取数据
                alert(data);    //弹出'I was there!'
            } else if (state === 0) {
                state = 1;
                iframe.contentWindow.location = "http://a.com/proxy.html";    // 设置的代理文件
            }  
        };
        iframe.src = 'http://b.com/data.html';
        if (iframe.attachEvent) {
            iframe.attachEvent('onload', loadfn);
        } else {
            iframe.onload  = loadfn;
        }
        document.body.appendChild(iframe);
    </script>
  3. 获取数据之后销毁这个iframe,释放内存;这也保证了安全(不被其余域frame js访问)。app

    <script type="text/javascript">
        iframe.contentWindow.document.write('');
        iframe.contentWindow.close();
        document.body.removeChild(iframe);
    </script>

总结起来即:iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操做。firefox

参考文章:window.name Transport、Session variables without cookies、使用 window.name 解决跨域问题、利用window.name实现跨域访问的基本步骤、克军写的样例。

相关文章
相关标签/搜索