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

如何使用postMessage获取跨域iframe内容并存储到父页面变量

实现逻辑

postMessage为双向通信机制,需补全两个缺失环节:

  1. iframe端收到父页请求后,将自身内容回传给父页
  2. 父页注册message事件监听,接收iframe回传的内容后赋值到变量
    同时需要增加iframe加载监听、源安全校验逻辑,避免出现消息丢失、安全风险。

修正后完整代码

父页(localhost:3000)

<iframe src="http://example.com" id="example"></iframe>

<script>
  let iframeCONTENT = null;
  
  const iframe = document.querySelector("#example");
  // 等待iframe加载完成后再发请求,避免监听未注册导致消息丢失
  iframe.addEventListener('load', () => {
    const iframeWindow = iframe.contentWindow;
    // 生产环境禁止使用*通配符,明确指定iframe的源地址
    iframeWindow.postMessage("requestContent", "http://example.com");
  })

  // 监听iframe回传的消息
  window.addEventListener('message', (e) => {
    // 安全校验:仅处理指定源的消息,防止恶意伪造消息
    if(e.origin !== 'http://example.com') return;
    // 赋值到目标变量
    iframeCONTENT = e.data;
    // 此处可继续处理拿到的内容
    console.log('iframe内容已保存:', iframeCONTENT);
  }, false)
</script>

iframe页(http://example.com)

<h1>Hello World!</h1>
<p>Blabla!</p>

<script>
    window.addEventListener("message", (e) => {
       // 安全校验:仅接受父页来源的请求
       if(e.origin !== 'http://localhost:3000') return;
       // 匹配请求指令,避免处理其他类型消息
       if(e.data === 'requestContent') {
         // 可按需调整返回内容:如需完整页面代码可替换为document.documentElement.outerHTML
         const content = document.body.innerHTML;
         // 回传内容到父页
         e.source.postMessage(content, e.origin);
       }
    }, false)
</script>

注意事项

  • 若需要传递DOM节点对象需先序列化为字符串,postMessage仅支持可结构化克隆的类型数据
  • 所有场景下都不建议使用*作为postMessage的目标源,明确指定源地址可规避绝大多数通信安全风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 03:54:02