iframe父子组件传值
父组件:index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<iframe src="iframe.html" width="200" height="200" id="iframe_demo"></iframe>
<input type="button" name="" id="" value="父向子传值" onClick="sendBtn()" />
</body>
<script type="text/javascript">
// 父接受子的值
/**
* 跨源通信-接收方
* @param {event} = [value]
* @param {function} = [value]
* @param {useCapture} 布尔可选 指定事件是否在捕获或冒泡阶段执行。
*/
window.addEventListener("message", function(data) {
console.log('父收到的数据:', data.data);
}, false);
// 父向子传值
function sendBtn() {
let iframe = document.getElementById('iframe_demo');
let json = {
name:'你好我是父'
};
iframe.contentWindow.postMessage(json, '*');
}
</script>
</html>
子组件:iframe.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="button" name="" id="" value="子向父传值" onClick="sendBtn()"/>
</body>
<script type="text/javascript">
function sendBtn(){
// 子向父传值
/**
* 跨源通信-发送方
* @param {massage} = [value]
* @param {targetOrigin} = [value]
*/
let json = {
name:'你好我是子'
};
window.parent.postMessage(json, '*');
}
// 子接收父的值
window.addEventListener("message", function(data) {
console.log('子收到的数据:', data.data);
}, false);
</script>
</html>

浙公网安备 33010602011771号