location.hash + iframe跨域

本文介绍了一种使用iframe和location.hash实现跨域通信的方法。通过在不同域间传递hash值,结合同域页面间的直接JS访问,实现了A域、B域和C域三者之间的数据交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现原理:

    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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值