1、html頁面
<div>
<iframe id="frame_child" name="frame_child" frameborder="no" width="100%" height="100%" style="min-height:1000px" scrolling="yes" src=""></iframe>
</div>
2、父頁面js代碼
<script type="text/javascript">
window.onload = function(){
//端口號是你自己的端口號
var url= "http://子頁面IP:8092/share.html" + "&_t=" + (new Date()).getTime();
$("#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), 'http://子頁面IP:8092');
console.log('發送成功');
},2000);
window.addEventListener("message", receiveMessage, false);
});
}
var receiveMessage = function(event) {
if (event.origin !== 'http://子頁面IP:8092'){
return;
}
console.log("子頁面有消息回來了");
console.log(event);
$("#frame_child").attr("height",accAdd(accMul(event.data,1),300) + 'px');
window.removeEventListener("message", receiveMessage, false);
}
</script>
2、子頁面js代碼
<script type="text/javascript">
$(function(){
window.addEventListener('message', function (event) {
const data = JSON.parse(event.data)
if (event.origin !== data.parentOrigin) {
return
}
// console.log('父發送了:' + data.msg)
// console.log('我返回頁面高度:' + document.body.scrollHeight)
event.source.postMessage(document.body.scrollHeight, event.origin)
}, false);
});
</script>
accAdd , accMul等避免精度丟失的方法參考
https://blog.csdn.net/qq_29777207/article/details/85252258
推薦一個公衆號
號主爲一線大廠架構師,CSDN博客專家,博客訪問量突破一千萬。主要分享Java、golang架構,源碼,分佈式,高併發等技術,用大廠程序員的視角來探討技術進階、面試指南、職業規劃等。15W技術人的選擇!