跨域名下的少量信息交互

问题描述

有两个站点,A站点需要根所B站点的一个状态决定是否展示B站的一个iframe,由于跨域问题,A站与B站无法进接进行通讯,所以设计了下面这个方案.

先上代码

站点A的页面

display页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        div { height: 200px; width: 100%; background: blue; }
    </style>
</head>
<body>
<div>header</div>
<iframe id="iframe" src="http://b.com/set.html" style="display:block;" height="0" width="100%" frameborder="0" scrolling="no"></iframe>
<div>footer</div>
<script>
    function callback(height)
    {
        document.getElementById("iframe").height = height
    }

</script>
</body>
</html>

callback页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
    var QueryString = {};
    QueryString.parse = function (qs)
    {
        var pairs = qs.split("&"), obj = {}, pair, i, param, value;
        for (i = 0; i < pairs.length; i++)
        {
            if (pairs[i] === "") continue;
            pair = pairs[i].split("=");
            param = decodeURIComponent(pair[0]);
            value = decodeURIComponent(pair[1]);
            if (obj[param] != null)
            {
                if ("[object Array]" != Object.prototype.toString.call(obj[param]))
                {
                    obj[param] = [obj[param], value];
                }
                else
                {
                    obj[param].push(value);
                }
            }
            else
            {
                obj[param] = value;
            }
        }
        return obj;
    };
    var search = QueryString.parse(location.search.slice(1));
    top.callback(search.height);
    location.href = search.redirect;
</script>
</body>
</html>

站点B的页面

set页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
    location.href = "http://a.com/callback.html?height=30&redirect=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttp%2Fb.com%2Ftarget.html";
</script>
</body>
</html>

target目标展示页面

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
hello world!
</body>
</html>

解析

A站的iframe先加载b站的set页面,由于B站可以更新set页面,所以set页面中参数可以随时变更.
set页面所需要做的就是把B站的一些信息,通过location.href的方式,带回A站,这里我们设置的接收地址是http://a.com/callback.html,
A站的callback被页面加载后,是可以自由的获取自身的URL的,也就是说,他可以获得由B站带来的参数.解析参数,执行相关动作,DEMO中,我设置了两个参数

  • height,用来告知a.com/display.html中的iframe高度的.
  • redirect用来回到B站地址,注意,这作为URL中的参数,URL链接需要经过encodeURIComponent编码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值