- 业务场景:两个不同端的项目,一个是pc端另一个是mobile端。pc端对业务数据展示需要直接使用mobile端的样式结构,所以利用ifarme直接嵌套mobile的页面实现pc端对其复用。
- 问题:如何能合适的设置ifarme高度,使得页面能完整展示。
- 注意:不能跨页面使用iframe.contentWindow.xxx操作ifarme里面的dom获取页面的高度然后设置给ifarme,因为这样的操作是属于跨页面操作dom是被跨域所限制的。
- 解决代码如下:
PC端向mobile端传递数据,监听mobile端页面渲染完之后的高度,然后设置对应的ifarme高度:
// PC端跨页面传递数据
const iframeFirst = document.getElementById('postStandIframeFirst');
if (iframeFirst) {
iframeFirst.contentWindow.postMessage(this.firstInt, httpMobileUrl);
}
const iframeSecond = document.getElementById('postStandIframeSecond');
if (iframeSecond) {
iframeSecond.contentWindow.postMessage(this.secondInt, httpMobileUrl);
}
window.addEventListener('message', (e) => {
const {height, actTaskKey} = e.data
// 动态设置iframe高度
if (typeof height === 'number') {
if (iframeFirst && actTaskKey === 'first_interview') {
iframeFirst.height = (height + 10) < 100 ? 2320 : (height + 10)
}
if (iframeSecond && actTaskKey === 'second_interview') {
iframeSecond.height = (height + 10) < 100 ? 2320 : (height + 10)
}
}
},)
mobile端接收数据进行渲染,然后向pc端传递页面渲染完之后的高度:
mounted() {
window.addEventListener('message', (e) => {
this.postStandardInfo = e.data || {}
this.$nextTick(() => {
const height = document.getElementById('app').clientHeight
const {actTaskKey} = this.postStandardInfo
const data = {
height,
actTaskKey
}
e.source.postMessage(data, e.origin)
})
})
}
效果图: