js,为什么这个postMessage无法向另一个网页发送信息


程序目标:点击“打开副本网页”按钮,然后点击“发送信息”向打开的网页发送信息,新开的网页监听并输出接收的信息。两个页面在同个文件夹下

网页1

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>主页</title>
</head>
<body>
    <button class="open-copy">打开副本网页</button>
    <button class="send-msg">发送信息</button>

    <script type="text/javascript">
        var openCopy = document.getElementsByClassName("open-copy")[0];
        var sendMsg = document.getElementsByClassName("send-msg")[0];
        openCopy.onclick = function(){
            newPage = window.open("practice2.html");
        };
        sendMsg.onclick = function(){
            newPage.postMessage("nihao","practice2.html");
        }

    </script>
</body>
</html>

网页2

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>副本</title>
</head>
<body>
    <button class="get-msg">接收打印信息</button>

    <script type="text/javascript">
        var getMsg = document.getElementsByClassName("get-msg")[0];
        window.addEventListener("message",function(e){
            newMsg = document.write(e.data);
            getMsg.onclick = function(){
                console.log(e.data);
            }
        },false);
    </script>
</body>
</html>


newsudhc3634140
浏览 2706回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP