postMessage event.source 不能使用

来源:3-14 通信类

六一888

2019-10-23

在子窗口中,console.log(event.source),出现 Uncaught DOMException: Blocked a frame with origin “http://localhost:3000” from accessing a cross-origin frame.
这样的报错,所以用了 window.parent 来代替 event.source,为什么 event.source 无法使用?

写回答

2回答

六一888

提问者

2019-10-26

<body>
    <button id="btn">send</button>
    <iframe src="http://localhost:3000/b.html" width="300px" height="300px"></iframe>
    <script type="text/javascript">
      var frame = document.querySelector('iframe');
      document.getElementById('btn').onclick = function() {
        frame.contentWindow.postMessage('hello', 'http://localhost:3000');
      }
      window.onmessage = function(event) {
        console.log(event.data);
      }
    </script>
  </body>


<body>
    <p id="show" style="width: 100px; height: 100px; background: red;"></p>
    <script type="text/javascript">
      var oP = document.getElementById('show');
      window.onhashchange = function() {
       oP.innerText = window.location.hash;
      }
      window.onmessage = function(event) {
        console.log(event.origin);
        console.log(event.data);
        console.log(event.source);
        // window.parent.postMessage('i love u', 'http://localhost:8000');
      }
    </script>
  </body>

//img.mukewang.com/szimg/5db41493098f9b3f15460196.jpg

0
0

快乐动起来呀

2019-10-26

这个是跨域造成的,你可以把代码贴出来我看下

0
3
六一888
回复
快乐动起来呀
是的,event.source===window.parent 结果为true,即便在 if 判断句中执行 console.log(event.source) 依然会报同样的错误,当我使用 event.source 代替 window.parent 时,由于 onmessage 事件一刷新就会被执行,所以一开始就会报“在“DOMWindow”上执行“postMessage”失败:提供的目标原点(“http://localhost:8000”)与接收窗口的原点(“http://localhost:3000”)不匹配。”的错误,所以我觉得使用 event.source 不是很好用。
2019-10-26
共3条回复

前端跳槽面试必备技巧 面试官全流程指导

一门让你能成功获取前端 Offer 的课程, 不只是技术,面试“技巧”也至关重要

4836 学习 · 830 问题

查看课程