postMessage的正确打开方式

先附上宝典地址
页面加载完成是重点
页面加载完成是重点
页面加载完成是重点

iframe测试

iframe嵌套不需要服务器启动也能成功,即file:///的路径;
第一个页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>与iframe用postMessage通信</title>
</head>
<body>
    第一个页面
    <div onclick="postIframe()">iframe通信</div>
    <iframe id="secondPage" src="http://*.*.*.*:8081/second.html" frameborder="0"></iframe>
    <script>
        function postIframe(){
            document.getElementById("secondPage").contentWindow.postMessage("手动发送", "http://*.*.*.*:8081");
        }
        // 这里未等到iframe加载完成就发送信息,是不会成功的
        document.getElementById("secondPage").contentWindow.postMessage("失败", "*");
        window.onload = function(){
            //这里是测试,所有origin用了*,实际生产中为了安全请设置正确的 origin ,
            //这个字符串由协议、“://“、域名、“ : 端口号”拼接而成。例如 “`https://example.org` (隐含端口 `443`)”
            document.getElementById("secondPage").contentWindow.postMessage("成功", "*");
        }
        var receiveMessage = function(event){
            console.log(event);
            if(event.origin){
                    //想做点什么!
            }
        };
        window.addEventListener("message", receiveMessage, false);
    </script>
</body>
</html>

第二个页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    第二个页面
    <script>
        var receiveMessage = function(event){
            console.log(event);
            if(event.orgin){
            }
            //这里接收到消息后立即就返回一条信息
            event.source.postMessage("how are you!", "*");
        }
        window.addEventListener("message", receiveMessage, false);
    </script>
</body>
</html>

window.open新打开一个窗口测试

这里需要用启动一个服务,file:///的路径似乎不起作用;
启动一个服务的方法很简单:
1.首先全局安装npm i -g http-server,然后在需要的文件夹直接打开cmd,运行http-server;
2.安装了python,python -m SimpleHTTPServer 8100(python3中命令python -m http.server 8100);类似的方式还可以在网上找找;
第一个页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>window.open新窗口通信</title>
</head>
<body>
    第一个页面
    <div onclick="openWin()">open window</div>
    <script>
        function openWin(){
            // 位置在同一个文件夹,非要搞事情放在不同的文件夹下?
            //当然可以写全域名
            var popup = window.open("./second.html");
            // 如果弹出框没有被阻止且加载完成
            popup.onload = function(){
                popup.postMessage("The user is 'bob' and the password is 'secret'", "*");
            }
        }
        var receiveMessage = function(event){
            console.log(event);
            if(event.origin){
                  // 做点事情
            }
        };
        window.addEventListener("message", receiveMessage, false);
    </script>
</body>
</html>

第二个页面同上一个
页面加载完成是重点
页面加载完成是重点
页面加载完成是重点

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容