H5 postMessage 示例
时间: 2024-10-15 14:04:32 浏览: 34
H5的postMessage()函数是一个用于在两个不同的同源窗口(或worker)之间发送消息的重要功能。它允许前端在浏览器环境中的跨域通信,而无需服务器介入。下面是一个简单的H5 postMessage示例:
```html
<!DOCTYPE html>
<html>
<body>
<div id="parentWindow">
<button onclick="sendToChild()">点击发送到子窗口</button>
</div>
<!-- 子窗口 -->
<iframe id="childWindow" src="child.html"></iframe>
<script>
function sendToChild() {
// 父窗口
var parent = window.parent;
// 发送的消息内容
var message = { action: 'hello', data: 'from parent' };
// 使用postMessage发送消息
parent.postMessage(message, '*');
}
// 子窗口接收消息
window.addEventListener('message', function(event) {
if (event.origin !== 'http://yourdomain.com') return; // 验证来源防止XSS攻击
console.log('Received:', event.data);
});
</script>
</body>
</html>
```
在这个例子中,`sendToChild`函数触发了一个事件,将包含`action`和`data`的对象作为参数传递给`postMessage`。子窗口(嵌套的`<iframe>`)通过监听`message`事件接收并处理来自父窗口的消息。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)