实现原理:
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