跨域的N种方法之window.name+iframe跨域实践

一、原理

  1、iframe内联框架的src属性跨域加载资源的能力

  2、window.name 值在不同的页面(甚至不同域名)加载后依旧存在(如果没修改则值不会变化),并且可以支持非常长的 name 值(2MB)或者说 window.name属性值在文档刷新后依旧存在的能力

二、总体框架及代码

  1、A域中的获取数据页:index.html

<!DOCTYPE html>
<html>
<head>
    <title>A域(window.name+iframe跨域解决方案)</title>
</head>
<body>

</body>
<script type="text/javascript">
    var ifr = document.createElement("iframe");
        ifr.style.display="none";
        ifr.src = "http://top.jiangqi.cn:8081/index2.html";
        document.getElementsByTagName("head")[0].appendChild(ifr);
    var flag = 0;
        ifr.onload = function(){
            if(flag == 0){
                flag = 1;
                 ifr.contentWindow.location = 'http://www.jiangqi.cn/windowName/proxy.html';
            }else{
                //获取数据
                console.log(JSON.parse(ifr.contentWindow.name))
                //释放内存,销毁iframe
                ifr.contentWindow.close();
                document.getElementsByTagName("head")[0].removeChild(ifr);
            }
        }
</script>
</html>

  2、A域中的代理页(空文档,只起到window.name转同域作用):proxy.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

</body>
</html>

  3、B域中的数据源页:index.html

<!DOCTYPE html>
<html>
<head>
    <title>window.name+iframe跨域解决方案)</title>
</head>
<body>

</body>
<script type="text/javascript">
    var person = {
        name:"蒋*",
        age:"26",
        education:"大学本科"
    }
    window.name = JSON.stringify(person)
</script>
</html>

三、参考

  1、https://www.tuicool.com/articles/viMFbqV

  2、https://segmentfault.com/a/1190000011145364

原文地址:https://www.cnblogs.com/helloNico/p/10642440.html