高程4上的postMessage是不是有错误?

69 阅读1分钟

1.开始的父页面http://127.0.0.1:5500/lslib.html

 <!DOCTYPE html>
 <html>
 <head>
     <title>Post Message</title>
 </head>
 <body>
     <div id='oo'>oo</div>
     <div>
         <iframe id="child" src="http://localhost:5500/onmessage.html"></iframe>
     </div>
 
     <script type="text/javascript">
         window.onload=function(){
             window.frames[0].postMessage('getcolor','*');
         }
        // 为子传父预留
         window.addEventListener('message',function(event){
            console.log(event.data)
            document.getElementById("oo").innerHTML = event.data;
        },false);
     </script>
 </body>
 </html>

长相: image.png

iframe http://127.0.0.1:5500/onmessage.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="ii">hhhhh </div>
    <script>
        window.addEventListener('message',function(event){
            console.log(event.data,event.origin)
            if(typeof event.data == 'string') {
                document.getElementById("ii").innerHTML = event.data;
            }
        },false);
    </script>
</body>
</html>

长相:

image.png

后续我修改了postMessage中第二个参数让他不为子iframe的src地址,子页面就监听不到data数据,如果子父页面都是同源的把第二个参数改为父页面的url,子页面也能拿到值,改为不同源的子页面就拿不到data数据。

image.png 这样去写也是可以拿到data的

image.png