跨页面通信postMessage和onmessage

简介

通常,对于两个不同页面的,只有当它们位于同协议、同域名、同端口时,才可以通信。而window.postMessage() 方法可以安全地实现跨源通信。

语法

发送:

otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow

其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象,或者父窗口的引用 window.opener

message

将要发送到其他 window的数据,可以是字符串也可以是对象。

targetOrigin

origin属性可以指定哪些窗口能接收到消息事件,格式为:协议+域+端口,如果设为 “*” 表示无限制,为了安全最好别设置为 “ * ”

接收:

window.onmessage = function(e){
    
      
    console.info("received msg: " + e.data);
    console.info("received msg: " + e.origin);
    console.info("received msg: " + e.source);
}
data

传过来的数据

origin

发送方窗口的origin

source

发送方窗口对象的引用,可以使用这个引用双向发消息

举例

在demo1页面有一个iframe,它的src指向demo2页面

从demo1发送一条消息给demo2,demo2收到消息后回复demo1消息:收到了

demo1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo1</title>
</head>
<body>
<iframe id="iframe" border="0"  src="http://192.168.1.210:8080/demo2.html"></iframe>

<br><br><br><br>
<hr>
<br><br><br><br>

<button onclick="pushMessage()">发送消息给iframe</button>
<br><br>
<div style="padding: 20px;border:1px solid green;">
    <span>ifram返回的消息为:</span>
    <p id="msg"></p>
</div>

<script>
    function pushMessage(){
     
     
        document.getElementById('iframe').contentWindow.postMessage("你好啊","http://192.168.1.210:8080")
    }

	// 接收iframe返回的消息
    window.onmessage = function (e) {
     
     
        document.getElementById('msg').innerText = e.data
    }
</script>
</body>
</html>
demo2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo2</title>
</head>
<body style="padding:20px;border: 1px solid red;">
    <span>iframe收到的消息为:</span>
    <p id="msg"></p>

<script>
    window.onmessage = function (e) {
     
     
        console.info("received from A is: " + e.data);
        document.getElementById('msg').innerText = e.data

        // 发送方窗口对象的引用
        var pWindow = e.source
		// 回复父窗口消息
        pWindow.postMessage("收到了","http://192.168.1.210:8080")
    }
</script>
</body>
</html>
运行后的效果图:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/dan_seek/article/details/104350133