一 . 父页面向子页面传值
通过H5的postMessage方法传值
首先,在父页面A中建立一个iframe,其中src要写好子页面B的地址,然后在A页面中写如下方法:
<iframe [src]="iframeSrc" id="overviewView" width="100%" height="100%" frameborder="0"></iframe>
var iframeSrc= "https://www.baidu.com";
var iframe: any = document.querySelector('#overviewView');
iframe.contentWindow.postMessage(msg,childDomain);
//iframe.contentWindow.postMessage({ type: 'iframeScroll', scrollTop: 850 }, '*');
childDomain与A的iframe的src地址不一样,childDomain是域,而src是域中的一个页面
msg是传输的信息,可以是字符串,也可以是对象。
上面的方法一定要写在一个函数中,并通过点击事件调用,如果希望iframe开始为空,点击后在设置src,
可以在设置src之后,通过setTimeout设置一定时间后在传输信息。
在子页面B中,通过对window添加事件获取传输过来的信息:
window.addEventListener('message', function (e) {
console.log(e);
if (e.data && e.data.type === 'iframeOnScroll') {
console.log(e.data.scrollTop);
}
}//,false
);
二.子页面传值给父页面
子页面
<body>
子级:B页面<br/>
<button id="b_button">B页面发送A页面数据</button><br/>
<script>
document.getElementById("b_button").onclick = function(){
var param = {'name':'admin'};
window.parent.postMessage(param,'*');
}
</script>
</body>
父页面
<body>
父级:A页面<br/><br/>
<iframe src="http://www.genetek.cc/iframe/b.html" width="500px" height="200px" id="iframe"></iframe>
<script>
window.addEventListener('message', function(e) {
alert(JSON.stringify(e.data));
console.log('获取子级B页面返回值:');
console.log(e.data);
})
</script>
</body>