跨标签页通信(七):postMessage
在现代 Web 开发中,跨标签页通信的需求越来越普遍。无论是实现多标签页之间的数据同步,还是构建实时协作功能,跨标签页通信都能极大地提升用户体验。今天,我们将探讨一种简单而强大的实现方式:window.postMessage。
一、什么是 window.postMessage?
window.postMessage 是一个用于跨窗口或跨标签页通信的 API。它允许一个窗口向另一个窗口发送消息,即使这两个窗口的来源不同。这种方法可以安全地实现跨源通信,而不会暴露窗口的 DOM 或 JavaScript 环境。
(一)特点
- 跨源通信:可以在不同来源的窗口之间安全地发送消息。
- 简单易用:API 简洁,易于上手。
- 事件驱动 :通过监听
message
事件接收消息。
(二)适用场景
- 多标签页数据同步:在多个标签页之间同步数据,如用户状态、实时消息等。
- 实时协作:多个用户在不同标签页上协作编辑文档或进行实时交互。
- 页面间通信:在父页面和弹出窗口之间通信。
二、使用 window.postMessage 实现跨标签页通信
(一)基本用法
window.postMessage
方法接受两个参数:
- 数据:要发送的消息,可以是字符串、对象等。
- 目标窗口的来源 :目标窗口的来源(
origin
),用于确保消息只发送到指定的窗口。如果目标窗口的来源不确定,可以使用*
作为通配符。
(二)发送消息
在页面一中,通过 window.postMessage
发送消息。
html
<!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>
</head>
<body>
<button id="popBtn">弹出新窗口</button>
<input type="text" id="content">
<button id="btn">发送数据</button>
<script>
const popBtn = document.querySelector("#popBtn");
const content = document.querySelector("#content");
const btn = document.querySelector("#btn");
let opener = null; // 用于保存 window.open 打开的窗口的引用
popBtn.onclick = function(){
opener = window.open("index2.html", "123123", "height=400,width=400,top=20,resizeable=yes");
}
btn.onclick = function(){
let data = {
value : content.value
}
// data 代表的是要发送的数据,第二个参数是 origin,使用 * 代表所有域
opener.postMessage(data, "*")
}
</script>
</body>
</html>
(三)接收消息
在页面二中,通过监听 message
事件接收消息。
html
<!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>
</head>
<body>
<p>这是页面二</p>
<script>
window.addEventListener("message", function(e){
console.log("接收到的消息:", e.data);
});
</script>
</body>
</html>
(四)效果
- 打开页面一,点击"弹出新窗口"按钮,打开页面二。
- 在页面一中输入消息并点击"发送数据"按钮。
- 页面二的控制台会打印出接收到的消息。
三、注意事项
(一)同源限制
虽然 window.postMessage
支持跨源通信,但为了安全起见,建议明确指定目标窗口的来源(origin
)。如果目标窗口的来源不确定,可以使用 *
作为通配符,但这样做会降低安全性。
(二)安全性
在接收消息时,应验证消息的来源和内容,以防止恶意攻击。可以通过检查 event.origin
和 event.source
来确保消息来自可信的窗口。
(三)性能影响
虽然 window.postMessage
的性能开销较小,但在高频率发送消息时,仍需注意对性能的影响。