问题描述
有两个站点,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
编码