本文主要是针对window.postMessage的使用
场景简述:父页面使用iframe嵌套了一个子页面,子页面操作后需要将数据返回父页面进行展示,父页面接收到消息后告诉子页面已经接收到消息。
window.postMessage的参数介绍
otherWindow.postMessage(message, targetOrigin, [transfer]);
- otherWindow:其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
- message:将要发送到其他 window的数据。
- targetOrigin:通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*"(表示无限制)或者一个URI。
- transfer(可选参数):是一串和message 同时传递的 Transferable 对象,这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。
1、parent.html
1、接收数据:监听message事件
2、使用iframe的contentWindow属性向子页面发送消息。
<!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>展示消息</title>
<style>
#parent {
width: 400px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="parent">
<div>
<span>我是父页面:</span>
<span id="text"></span> // 用于展示子页面传递的内容
</div>
<iframe id="chile" src="http://127.0.0.1:5500/chile.html" frameborder="0"></iframe>
</div>
<script>
const ifram = document.getElementById("chile");
const text = document.getElementById('text');
// 子页面
chile.onload = () => {
window.addEventListener('message', event => {
console.log("message", event);
const data = event.data.res;
text.innerText = data;
const params = {
res: "父页面已经收到消息"
}
chile.contentWindow.postMessage(params, '*')
}, false)
}
</script>
</body>
</html>
2、chile.html
1、使用 window.parent.postMessage(data, '*');发送数据。
<!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>发送消息</title>
<style>
#chile {
height: 50px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="chile">
<div>
<span>我是子页面:</span>
<span id="chileText"></span> // 用于展示父页面传递发内容
</div>
<button id="chileBtn">点击发送</button>
</div>
<script>
const chileBtn = document.getElementById("chileBtn");
const chileText = document.getElementById("chileText");
chileBtn.onclick = () => {
const params = {
res: "我来自子页面"
}
window.parent.postMessage(params, "*")
}
window.addEventListener("message", event => {
console.log('chile---message---', event);
chileText.innerText = event.data.res;
}, false)
</script>
</body>
</html>