avatar
fireworks99
keep hungry keep foolish

window.postMessage

window.postMessage()方法可以安全地实现跨域通信

何为跨域

同源:如果两个URL的协议(protocol,如ftp、http)、主机(host,如blog.csdn.net)、端口号(port,如80、5500)三者都相同,那么这两个URL是同源。否则两者的通信需要跨域。

值得注意的是,域(domain)、源(origin)两者不是一回儿事,比如https://blog.csdn.net,其域document.domaincsdn.net,而其源之主机window.location.hostblog.csdn.net

1.用法

发送消息的页面:

targetWindow.postMessage(data, targetOrigin, [transfer]);

接收消息的页面

window.addEventListener("message", function(e) {
    xxx = e.source;
    xxx = e.data;
})

window.addEventListener("message", function(e) {})

等效于

window.onmessage = function(e) {}

2.应用

发送消息的页面

file:///Users/xxx/xxx/daily/postMessage/postMessage.html

<body>
    <textarea name="text" id="text" cols="30" rows="10"></textarea>
    <button id="btn">发送</button>

    <!-- <a href="http://127.0.0.1:5500/daily/postMessage/onMessage.html" target="_blank">打开接收页面</a> -->
    <a href="javascript:window.open('http://127.0.0.1:5500/daily/postMessage/onMessage.html')">打开接收页面</a>

    <script>
        let text = document.getElementById("text");
        let btn = document.getElementById("btn");
        let msgPage = null;
        btn.onclick = function () {
            msgPage && msgPage.postMessage(text.value, '*');
        }
        window.addEventListener("message", function(e) {
            msgPage = e.source;
            document.title = e.data;
            text.value = e.data;
        })
    </script>
</body>

接受消息的页面

http://127.0.0.1:5500/daily/postMessage/onMessage.html

<body>
    <textarea name="text" id="text" cols="30" rows="10"></textarea>
    <button id="btn">发送</button>

    <script>

        console.log(window.opener);

        opener && opener.postMessage("新页面打开成功", '*');

        let text = document.getElementById("text");
        let btn = document.getElementById("btn");

        btn.onclick = function () {
            opener && opener.postMessage(text.value, '*');
        }
        window.addEventListener("message", function(e) {
            document.title = e.data;
            text.value = e.data;
        })
    </script>
</body>

关于window.opener:返回打开当前窗口的那个窗口的引用,例如:在 window A 中打开了 window B,B.opener 返回 A.

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy