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>
00 -
快乐动起来呀
2019-10-26
这个是跨域造成的,你可以把代码贴出来我看下
032019-10-26
相似问题