js postMessage不工作

1,026 阅读1分钟

JavaScript高级程序设计 第四版 20章第二节内容。 20.2 跨上下文消息 内容学习笔记

故障现场

当前页面为 index2.html,本地页面运行地址为 http://localhost:52330/Chapter20/index2.html, 代码如下

<!DOCTYPE html>
<html>
  <head>
    <title>index2</title>
  </head>
  <body>
    <iframe src="http://localhost:52330/Chapter20/index.html" id="myframe"></iframe>
    <script>
      let iframeWindow = document.getElementById('myframe').contentWindow;
      console.log('iframeWindow contextWindow: ', iframeWindow);
      iframeWindow.postMessage('A secret', 'http://localhost:52330/Chapter20/index.html');
    </script>
  </body>
</html>

页面中使用 iframe 标签显示 index.html 页面,效果如下

index.html 内容

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body>
    index.html
    <script>
      window.addEventListener('message', (event) => {
        console.log('1')
        console.log(event.origin)
      })
    </script>
  </body>
</html>

当前代码写法在 index2.html 中使用 postMessage 页面运行后,在 index.html 中监听 message 无反应。

原因分析

  • 可能代码写法哪里有误
  • 可能由于 index2.html 代码块执行太快,iframe 中内容还未完全加载和渲染就结束了

解决方案

  • 写法问题,通过核对书和MDN没有不一样的地方
  • 尝试使用 setTimeout 后发现这个问题解决了,确定了是渲染加载的问题

最后 index2.html 代码调整部分如下, index.html 就可以监听到消息了

setTimeout(() => {
  console.log('1000ms')
  iframeWindow.postMessage('A secret', 'http://localhost:52330/Chapter20/index.html');
}, 1000)