如何向延迟加载的iframe发送消息且不违反CORS策略?
跨域iframe postMessage失败问题解决
错误原因
控制台报错核心问题:设置postMessage的目标origin为http://site2.example.com,但调用时iframe的contentWindow origin仍是http://site1.example.com。这是因为设置iframe的src后页面不会立刻加载完成,此时iframe处于初始空状态(同源site1),直接执行postMessage就会触发origin不匹配错误。
修复方案
必须等待iframe完全加载完成后,再发送消息。修改site1的index.html代码,给iframe添加load事件监听,在回调中执行postMessage:
<html> <head> <script type="text/javascript"> function loadIFrame() { console.log( "loading site2 iframe ..." ); const iframe = document.getElementById('myiframe'); iframe.src = "http://site2.example.com"; // 监听iframe加载完成事件,确保origin匹配后再发消息 iframe.addEventListener('load', function() { console.log( "sending message from site1 to site2 ..." ); iframe.contentWindow.postMessage( "Hello World!", 'http://site2.example.com'); }); } </script> </head> <body> <h2>Site1</h2> <a href="#" onclick="loadIFrame()">load iframe</a> <br/><br/><br/> <iframe id="myiframe" style="width:600px; height: 400px;"></iframe> </body> </html>
额外说明
- Nginx CORS配置无需调整:postMessage的跨域机制和CORS无关,当前site2的CORS配置是针对AJAX请求的,不影响iframe的postMessage通信。
- Referrer Policy无需修改:
strict-origin-when-cross-origin仅控制referrer的传递规则,和postMessage的origin验证没有关联。
内容的提问来源于stack exchange,提问作者Steve Maring
相关产品推荐
相关产品推荐

