七日打卡-窗口间通信postMessage

1,457 阅读1分钟

在前端应用中,窗口间的通信用的地方还是挺多的,比如弹出qq登录认证窗。

postMessage语法

window.postMessage(msg,targetOrigin)

注意postMessage要通过window对象调用!因为这里的window不只是当前window,大部分使用postMessage的时候,都不是本页面的window,而是其他网页的window!如:

  1. iframe的contentWindow
  2. 通过window.open方法打开的新窗口的window
  3. window.opener

如果你使用postMessage时没有带window,那么,你就是用的本页面的window来调用了它。

参数说明

msg

这就是要传递的消息了。它可以是一切javascript参数,如字符串,数字,对象,数组,而不是和json一样只局限于字符串。

targetOrigin

这个参数称作“目标域”,注意啦,是目标域不是本域!比如,你想在2.com的网页上往1.com网页上传消息,那么这个参数就是“1.com/”,而不是2.com.

另外,一个完整的域包括:协议,主机名,端口号。如:g.cn:80/

window.open方法会返回一个窗口对象,使用这个对象可以向子窗口发送消息,而子窗口可以通过window.opener向父窗口发送消息,示例如下: index.html

<body>
    <button onclick="opwin()">打开</button>
    <script type="text/javascript">
    function opwin() {
        //保留窗口对象
        var popup = window.open("test.html", "_blank");
    }
    function receiveMessage(event) {
        //event.origin是指发送的消息源,一定要进行验证!!!
        if (event.origin !== "http://localhost")return;
        //event.data是发送过来的消息。
        console.log(event.data);
        //event.source是指子窗口,主动向子窗口发送消息可以用popup
        //postMessage有两个参数,消息和自己的源(例如http://www.baidu.com),自己的源应该和目标源相同。否则发送会失败。
        event.source.postMessage("我是主窗口,我接收到消息了",window.location);
    }
    //添加消息接收函数
    window.addEventListener("message", receiveMessage, false);
    </script>
</body>

test.html

<body>
    <button onclick="send()">发送</button>
    <script type="text/javascript">
    function send() {
        //window.opener指的就是父窗口(打开本窗口的窗口)
        window.opener.postMessage("我是子窗口,向主窗口发送消息", window.location);
    }
    function receiveMessage(event) {
        if (event.origin !== "http://localhost")return;
        console.log(event.data);
    }
    window.addEventListener("message", receiveMessage, false);
    </script>
</body>

由于postMessage是通过网络协议,所以不能以直接在浏览器打开html的方式进行调试。而是应该放在服务器上,走网络协议。