location.hash+iframe 跨域解决方案

利用location.hash和iframe可以解决完全跨域的问题。其原理是利用location.hash传值,创建定时器,坚持hash的变化,执行相应的操作。
下面我们来完成一个案例:
在bao.com域名下有个index.html, 在index.html中通过iframe引入hui.com域名下header.html。使index.html和header.html可以相互通信。

index.html代码:

<html>
<meta charset="UTF-8" />
<h1>通过IFRAME 和 location.hash 进行javasript 跨域</h1>

引入header.html
<iframe id="iframe" src="http://www.hui.com/header.html"></iframe>
<input type="button" onClick="changecolor()" value="change color" id="btn" />
<script>
    var iframe = document.getElementById('iframe');
    var _timeid = setInterval(checkHash, 1000);function checkHash() {
    switch (location.hash) {
        case '#mainred':
            document.getElementById("btn").style.color = "red";
            break;
        }
    }

    function changecolor() {
        iframe.src = 'http://www.hui.com/huanhuba/modelWebsite/js/iframe/hash/header.html#red';
    }
</script>
</html>

hui.com下的 header.html代码:

<html>
<meta charset="UTF-8" />
<body>
<a href="javascript:;" id="btn">点击改变主页面按钮颜色</a>
<iframe src="http://www.bao.com/huanhuba/modelWebsite/js/iframe/hash/crossdomain.html" width="" height="" id="cdiframe" style="display: none;"></iframe>
<script>
    var _timeid = setInterval(checkHash, 1000);
    function checkHash() {
        switch (location.hash) {
            case '#red':
            callback();
            break;
        }
    }
    function callback() {
        document.getElementById("btn").style.color = "red";
    }

    document.getElementById("btn").onclick = function(){
    document.getElementById("cdiframe").src = document.getElementById("cdiframe").src + "#mainred";
};
</script>
</body>
</html>

现阶段index.html中可以更改引入的iframe的src的hash。header.html中通过定时器判断hash值的变化,做出相应的操作。但是在header.html不可以直接操作index.html的hash。如果直接用parent.locatin.hash = name;会出现
111111113324禁止跨域操作
此时需要引入一个代理文件(crossdomain.html),此文件与index.html同域,因此,index.html可以和crossdomian.html相互通信。通过在header.html中改变crossdomain.html的hash,在crossdomain.html中监听
hash的变化,在通过parent.parent.location.hash改变index.html的hash值。

crossdomain.html代码:

<html>
    <meta charset="UTF-8" />
    <script>

        /****crossmain 和  index在同一域名下可以相互通信**************/

        var _timeid = setInterval(checkHash, 1000);
        function checkHash(){
            parent.parent.location.hash = self.location.hash.substring(1);
        }

    </script>
</html>

location.hash + iframe跨域的优点:
1.可以解决域名完全不同的跨域
2.可以实现双向通讯

location.hash + iframe跨域的缺点:
location.hash会直接暴露在URL里,并且在一些浏览器里会产生历史记录,数据安全性不高也影响用户体验。另外由于URL大小的限制,支持传递的数据量也不大。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值