本地环境下主页面向iframe发送消息无响应问题求助
问题解决:主页面向iframe发送消息无响应
问题场景
在localhost同一文件夹下有main.php和iframe.php,尝试从主页面向iframe发送消息但无响应,已尝试多种target origin设置。
现有代码
main.php代码
<body> <iframe src="iframe.php" class="iframe"></iframe> </body> <script> const iframe = document.querySelector('.iframe'); iframe.contentWindow.postMessage("message sent from localhost/mainpage.php","http://localhost/iframe.php"); </script>
iframe.php监听代码
window.onmessage = function(event) { alert(event.data); }
问题原因及修复方案
1. 发送时机过早
主页面在iframe尚未加载完成时就调用了postMessage,此时iframe内的window.onmessage事件还未绑定,导致消息无法被监听。
修复方式:监听iframe的load事件,待iframe加载完成后再发送消息:
<body> <iframe src="iframe.php" class="iframe"></iframe> </body> <script> const iframe = document.querySelector('.iframe'); iframe.addEventListener('load', () => { iframe.contentWindow.postMessage("message sent from localhost/mainpage.php", "http://localhost"); }); </script>
2. targetOrigin设置错误
postMessage的第二个参数是目标文档的源(origin),而非具体文件路径。正确的origin格式是协议://域名:端口(端口默认80可省略),同一文件夹下的iframe源就是http://localhost。
测试场景下也可以临时用*(允许发送到任意源,生产环境禁止使用,存在安全风险)。
额外安全建议
在iframe的消息监听函数中增加源验证,避免接收未知来源的消息:
window.onmessage = function(event) { if (event.origin === "http://localhost") { alert(event.data); } }
内容的提问来源于stack exchange,提问作者woodfile
相关产品推荐
相关产品推荐

