當我們想通過iframe中的內(nèi)容自動改變iframe的高度時可能會想到使用load方法獲取到iframe頁面中的高度
<iframe
name="web" width="100%" frameborder=0 height="0"
src="http:xxx.com" id="web" onload="this.height=web.document.body.scrollHeight">
</iframe>
這種方法在不跨域的情況下是可以的,但是涉及到跨域的話會出現(xiàn)這樣的一個報錯
Uncaught DOMException: Blocked a frame with origin "http://127.0.0.1:8080" from accessing a cross-origin frame.
at HTMLIFrameElement.onload (http://127.0.0.1:8080/test1.html:16:28)
上網(wǎng)查閱了很多資料介紹使用window.postMessage()
方法,
/*test1.html 這是父頁面 127.0.0.1:8080*/
<div>這是父頁面</div>
<iframe name="web" width="100%"
frameborder=0 height="0"
scrolling="no"
src="http://172.16.1.17:8080/test2.html"
id="web">
</iframe>
<script>
window.onload = function() {
var iframe = document.getElementById('web');
iframe.contentWindow.postMessage("hello", "http://172.16.1.17:8080"); //將hello傳遞到iframe中
function receiveMessage(event){
if (event.origin !== "http://172.16.1.17:8080")
return;
console.log(event)
iframe.setAttribute("height",event.data);
}
window.addEventListener("message", receiveMessage, false); //獲取iframe傳來的信息
}
</script>
/*test2.html 這是iframe頁面 172.16.1.17*/
<div>這是iframe</div>
<script>
window.onload = function(){
var height = document.body.scrollHeight+20;
function receiveMessage(
if (event.origin !== "http://127.0.0.1:8080")
return;
event.source.postMessage(height,event.origin);//設(shè)置向父頁面?zhèn)鬟f的值
console.log(event);
}
window.addEventListener("message", receiveMessage, false);
}
</script>
其實看這個demo挺簡單,但是這里有幾個需要注意的坑
- text2.html在瀏覽器打開后是沒法成功,在這里我卡了很長時間
- 兩個頁面之間存在聯(lián)系(一般是父子關(guān)系),不能在瀏覽器中直接輸入兩個頁面的地址,a鏈接跳轉(zhuǎn)也是不行的
這里是查閱的一些資料
MDN介紹postMessage https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
別人的經(jīng)驗(推薦) https://github.com/Monine/monine.github.io/issues/2