You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用postMessage跨域通信时报Blocked a frame with origin错误求助

排查修复方案

  • 优先检查postMessage触发时机:你当前是获取iframe元素后直接调用contentWindow.postMessage,若iframe尚未完成加载时访问contentWindow属性会直接触发跨域报错。请改为监听iframe的load事件后再执行消息发送逻辑,示例代码如下:
const x = document.querySelector('iframe');
x.addEventListener('load', () => {
  const xWin = x.contentWindow;
  // 生产环境请将第二个参数替换为iframe的实际域名,禁止使用*
  xWin.postMessage("message", "*");
});
  • 检查iframe端origin校验规则:你当前iframe内的消息监听逻辑只允许的origin为https://axe-uat.unileversolutions.com/,但报错信息显示你的主站origin为myMainPage.com,二者不匹配会导致消息被丢弃。请先打印实际收到的event.origin值,再修改为匹配你主站的校验规则,示例如下:
window.addEventListener('message', event => {
  // 调试阶段先打印实际来源origin,确认后再修改校验规则
  console.log('实际消息来源origin:', event.origin);
  if (event.origin === '替换为你实际的主站origin') { 
    console.log(event.data); 
  } else {
    return; 
  } 
});
  • 检查iframe标签的sandbox配置:如果你的iframe标签添加了sandbox属性,需要同时配置allow-scripts和allow-same-origin权限,否则也会触发跨域拦截,示例配置:
<iframe src="你的iframe页面地址" sandbox="allow-scripts allow-same-origin"></iframe>

内容的提问来源于stack exchange,提问作者Alban denica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 13:00:03