跨域(六)——window.name

window.name也可以进行跨域数据传输。

下面是相应的代码,evil.html跨域读取foo.html的数据,其中proxy.html和evil.html同域,没有任何内容。

evil.html:

<script type="text/javascript">
    var flag= 0;
    var iframe = document.createElement('iframe');
    iframe.src = 'http://www.foo.com:8081/langtao/foo.html';
    document.body.appendChild(iframe);
    if (iframe.addEventListener) {
        iframe.addEventListener('load', hadle,false);
    } else {
        iframe.attachEvent('onload',hadle);
    }
    function hadle() {
        if (flag===1) {
            var data = iframe.contentWindow.name;    // 读数据
            alert(data);    //显示跨域数据
            //清理工作
            iframe.contentWindow.document.write('');
            iframe.contentWindow.close();
            document.body.removeChild(iframe);
        } else if (flag === 0) {
            flag = 1;
            iframe.contentWindow.location = "http://www.evil.com:8081/langtao/proxy.html";    // 设置的代理文件,proxy.html与evil.html同域
        }  
    };
</script>

foo.html:

<script type="text/javascript">
    window.name='我来自foo';    // name 属性可设置或返回存放窗口的名称的一个字符串,这里是我们要传输的数据
</script>
原文地址:https://www.cnblogs.com/aaron-shu/p/4175793.html