最近项目中需要对接企业微信,需要把原本app的功能搬到H5中,无奈中需要嵌入一块定制模块,开发太废时,无奈又要搞iframe。
首先时同源策略下(不跨域的做法)
<iframe
id="ifrma2"
name="ifrma2"
width="100%"
height="100%"
:src="iframeUrl"
@load.once="IFload"
></iframe>
vue写的, 原生可以直接用window.onload = functiong(){}
const IFload = () => {
var oIframe: any = (<HTMLElement>document.getElementById("ifrma2"))
try{
// console.log(oIframe.contentDocument)
const bodyDom = oIframe.contentWindow || oIframe.contentDocument.parentWindow;
state.height = bodyDom.document.body.scrollHeight || bodyDom.document.documentElement.scrollHeight
// console.log(bodyDom, state.height)
} catch (e) {
console.log(e)
}
oIframe.style.height = state.height
}
直接获取iframe内body的高度,赋值给iframe
现在是跨域(非同源)的解决办法:
需要子页面调用父默认的方法,父页面监听方法的执行来解决:重点 postMessage()
父页面iframe
<iframe
id="ifrma2"
name="ifrma2"
width="100%"
height="100%"
:src="iframeUrl"
@load.once="IFload"
></iframe>
// js监听嵌入页面调用时触发
const IFload = () => {
window.addEventListener('message', function(event) {
// alert(event.data)
// console.log(event)
if (event.origin === "http://localhost:8080") {
// alert(even
(<HTMLElement>document.getElementById("ifrma1")).style.height = event.data + "px";
}
})
}
嵌入子页面(页面加载完毕后再执行)
var hashH = document.documentElement.scrollHeight; //获取自身高度
// 全局下的parent其实是父页面的对象,所以调用postMessage()调用的也就是父级页面的方法,
window.parent.postMessage(hashH, "*");
调用后父页面拿到子页面传过来的高度,动态赋值,可用onload()事件处理,多次调用能实现懒加载页面多测高度变化的传递;
还可以用
window.onresize = () =>{} 监听页面高度变化的方法取监听