解决Iframe跨域高度自适应,利用window.postMessage()实现跨域消息传递页面高度(JavaScript)

在iframe跨域引用高度自适应这块写的js方式都试了不管用,最终使用的是window.postMessage() 跨域获取高度 传递信息

1.首先,在主页面上使用iframe引入子页面:也就是A.html页面引入B.html页面,下面看看A.html解决Iframe跨域高度自适应,利用window.postMessage()实现跨域消息传递页面高度(JavaScript)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
*{
padding: 0;
margin: 0;
}
</style>
<body>
<div>Hello! Is A.Html</div> <div align=center>
<iframe Id="frame_child" width="100%"></iframe>
</div>
</body>
</html>
<script>
$(function() {
window.onload = function() {
var url = "http://liting397.cn/"; //要访问子类调用地址
$("#frame_child").attr("src", url);
$("#frame_child").load(function() {
setTimeout(function() {
var frame = document.getElementById("frame_child").contentWindow;
var message = {
parentOrigin: window.origin,
msg: "收到请回复"
};
frame.postMessage(JSON.stringify(message), url);
console.log('发送成功');
}, 2000);
window.addEventListener("message", receiveMessage, false);
});
}
var receiveMessage = function(event) {
//if (event.origin !== event.data.Domain)
// return;
console.log("子页面有消息来了");
$("#frame_child").attr("height", event.data + 'px');
window.removeEventListener("message", receiveMessage, false);
}
})
</script>

2.子页面代码块js下边是B.html页面,B.html页面

解决Iframe跨域高度自适应,利用window.postMessage()实现跨域消息传递页面高度(JavaScript)

<script>
//本ifram为自适应js 使用postMessage 像父类传递消息
$(function() {
window.addEventListener('message', function(event) {
const data = JSON.parse(event.data)
if (event.origin !== data.parentOrigin) {
return
}
event.source.postMessage(document.body.scrollHeight, event.origin);
}, false);
});
</script>

这里是写好的ifram引用地址 可以参考  http://liting400.cn/

上一篇:[ 转 ]jquery的ajax和getJson跨域获取json数据


下一篇:How those spring enable annotations work--转