同域 iframe 父子间传值
父页面
<html>
<head>
<script type="text/javascript">
function say(){
alert("parent.html");
}
function callChild(){
myFrame.window.say();
myFrame.window.document.getElementById("button").value="调用结束";
}
</script>
</head>
<body>
<input id="button" type="button" value="调用child.html中的函数say()" onclick="callChild()"/>
<iframe name="myFrame" src="child.html"></iframe>
</body>
</html>
子页面
<html>
<head>
<script type="text/javascript">
function say(){
alert("child.html");
}
function callParent(){
parent.say();
parent.window.document.getElementById("button").value="调用结束";
}
</script>
</head>
<body>
<input id="button" type="button" value="调用parent.html中的say()函数" onclick="callParent()"/>
</body>
</html>
跨域 iframe 父子间传值
父页面
<template>
<div>
<iframe
:src="iframesrc"
id="a-page"></iframe>
</div>
</template>
<script>
export default {
computed:{
iframesrc:function(){
let iframesrc = "http://b.com"
return iframesrc
}
},
created () {
// 得到B传来的值
window.addEventListener('message',function(e){
console.log("B DOM的高度", e.data)
},false);
// 监听A页面的事件,发送给B
window.addEventListener('scroll', function () {
let iframe = document.getElementById('a-page');
let json = {
scrollTop: scrollTop,
windowHeight: windowHeight,
};
iframe.contentWindow.postMessage(json, '*');
});
}
}
</script>
子页面
<template>
<div>
<div id="b-page"></div>
</div>
</template>
<script>
export default {
mounted() {
// 获取到B页面的值,发送给A
let _this = this
let b_pageH = document.getElementById('b-page').scrollHeight;
window.parent.postMessage(b_pageH, '*');
// 得到A页面的值
window.addEventListener('message',function(e){
console.log("e.data.scrollTop", e.data.scrollTop)
console.log("e.data.windowHeight", e.data.windowHeight)
},false);
}
}
</script>
标签:function,父子,window,let,iframe,data,传值,页面
From: https://blog.51cto.com/u_14914383/7548628