The final effect is as follows
- Click the parent page button to pass the value to the child page
2. Click the sub-page button to pass the value to the parent page
code show as below:
parent page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2>我是父页面:</h2>
<div style="display: flex; flex-direction: column; align-items: flex-start">
<button onclick="handleMessage()">发送给子组件</button>
<iframe
src="http://192.168.10.68:9997/iframe/zi.html"
frameborder="0"
id="tempId"
></iframe>
</div>
<script>
var docHeight = 0;
function handleMessage(e) {
// 写法一
let target = document.getElementById("tempId");
target.contentWindow.postMessage(
"传递给子页面的数据",
"http://192.168.10.68:9997/iframe/zi.html"
);
// 写法二
// let target = window.frames[0];
// target.postMessage(
// "传递给子页面的数据",
// "http://192.168.10.68:9998/iframe/zi.html"
// );
}
// 接收子页面发送的message信息
window.addEventListener("message", (data) => {
console.log("接收来自子页面,", data);
});
</script>
</body>
</html>
Subpage
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="handleMessage()">发送给父页面</button>
<script>
function handleMessage(e) {
let target = document.getElementById("tempId");
window.parent.postMessage("传递给父页面的内容", "*");
}
// 接收父页面发送的message信息
window.addEventListener("message", (data) => {
console.log("接收来自父页面,", data);
});
</script>
</body>
</html>