location.hash + iframe跨域

4 篇文章 0 订阅

实现原理:

    a欲与b跨域相互通信,通过中间页c来实现。 三个页面,不同域之间利用iframe的location.hash传值,相同域之间直接js访问来通信。

具体实现:

    A域:a.html -> B域:b.html -> A域:c.html,a与b不同域只能通过hash值单向通信,b与c也不同域也只能单向通信,但c与a同域,所以c可通过parent.parent访问a页面所有对象。

代码实例:

a.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>ehz-app</title>
  </head>
  <body>
    <iframe id="iframe" src="http://192.168.1.10/php_demo/b.html" style="display:none;"></iframe>
    <script>
        var iframe = document.getElementById('iframe');
        // 向b.html传hash值
        setTimeout(function() {
            iframe.src = iframe.src + '#user=admin';
        }, 1000);
        // 开放给同域c.html的回调方法
        function onCallback(res) {
            console.log("a.html, res:" + res )
            alert('data from c.html ---> ' + res);
        }
    </script>
  </body>
</html>

b.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>ehz-app</title>
  </head>
  <body>
    <iframe id="iframe" src="http://192.168.1.10/php_demo/c.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');
    // 监听a.html传来的hash值,再传给c.html
    window.onhashchange = function () {
     console.log("b.html")
     console.log(location.hash);
        iframe.src = iframe.src + location.hash;
    };
</script>
  </body>
</html>

c.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>ehz-app</title>
<script>
    // 监听b.html传来的hash值
    window.onhashchange = function () {
        // 再通过操作同域a.html的js回调,将结果传回
        console.log("c.html")
        window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
    };
</script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

运行截图:

访问a.html:http://192.168.1.10/php_demo/a.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值