如何校验window.addEventListener('message')接收的消息是否来自特定注入iframe
Chrome扩展判断postMessage是否来自指定注入iframe的解决方案
你之前用e.target == appIframeContainer判断失效的核心原因是:message事件的target指向的是接收消息的window对象(也就是content script运行的顶层页面window),和发送消息的iframe元素没有关联,所以这个判断永远返回false。
最优解决方案
直接通过消息事件的e.source属性判断即可,e.source指向发送该消息的window对象,你注入的iframe对应的window对象就是appIframeContainer.contentWindow,两者全等对比即可100%确定消息来源,不需要依赖域名校验,也不需要靠消息格式做兜底校验。
修正后的代码
content script 侧
// 这里替换为你实际创建/获取iframe元素的逻辑 const appIframeContainer = document.createElement('iframe') document.body.appendChild(appIframeContainer) window.addEventListener("message", function (e) { // 非目标iframe发送的消息直接跳过 if (e.source !== appIframeContainer.contentWindow) return // 原有业务逻辑,可按需简化 if (e.data.toString().includes("test")) { const data = JSON.parse(e.data); if (data?.test?.message === "toggleApp") { toggleApp(); } } })
iframe 侧代码无需修改,保持原有逻辑即可
parent.window.postMessage( JSON.stringify({ test: { message: "toggleApp", }, }), "*", [] );
注意事项
- 建议给iframe添加
load事件监听,确保contentWindow属性已初始化后再执行逻辑判断,避免出现对比undefined的异常。 - 如果后续有更高的安全要求,可以把
postMessage的第二个参数从*替换为你iframe加载的实际域名,进一步缩小消息广播范围。
内容的提问来源于stack exchange,提问作者Rohan Keskar18
相关产品推荐
相关产品推荐

