首页 > 解决方案 > postMessage() 到子窗口无法发布

问题描述

我正在尝试将消息从父窗口发布到它打开的子窗口。但是,该消息未发布。

在父窗口脚本中:

function editAnnotation(annotKey){
    var annotString = annotToString();

    //open up the child window addAnnot.html.
    var editAnnotWindow = window.open("editAnnot.html", "Ratting","width=200,height=400,0,status=0,scrollbars=1");

    //send a message containing all the info from the current field. This message will cause all the fields to be prepopulated w info from annotation
    editAnnotWindow.postMessage(annotString, '*');
}

在子窗口脚本中:

window.onload = addListeners();

/***********************************************************************
*
* Function that adds listeners for messages
*
*/
function addListeners() {

  console.log("addListeners() called");
  window.addEventListener('message', parseMessage, false);//listens for messages from the index.html file page

}


function parseMessage(event){
        console.log("parseMessage() called");
}

addListeners() called已记录,但未记录parseMessage() called

我已经尝试过:

  1. 改变函数的顺序。

  2. 打开子窗口时发布消息。

例如:

var newWindow = window.open("file.html").postMessage("message string", '*');

标签: javascript

解决方案


postMessage太早在开启者窗口中打电话了;在脚本开始在打开的窗口中执行之前。

这是一个最小的工作示例,说明您可以采取哪些措施来解决此问题。打开的窗口可以告诉开启者何时准备好接收消息window.opener.postMessage

索引.html

<html>
<head>
  <meta charset="utf-8"/>

  <script>
    window.onload = function () {
      // set this to YOUR domain in production!!
      targetOrigin = '*'; 

      var openedWindow = window.open(
        "popup.html",
        "popup",
        "width=640,height=480"
      );

      function handleMessage (event) {
        if (event.data === 'openedReady') {
          document.body.innerHTML += '<br />';
          document.body.innerHTML += 'got event from opened window!';
          openedWindow.postMessage('openerMessage', targetOrigin);
        }
      }

      window.addEventListener('message', handleMessage, false);
    }
  </script>
</head>
<body>hi</body>
</html>

popup.html

<html>
<head>
  <meta charset="utf-8"/>

  <script>
    window.onload = function() {
      // set this to YOUR domain in production!!
      targetOrigin = '*'; 

      function handleMessage(event) {
        if (event.data === 'openerMessage') {
          document.body.innerHTML += '<br />';
          document.body.innerHTML += 'got event from opener window!';
        } 
      }

      window.addEventListener('message', handleMessage, false);

      window.opener.postMessage('openedReady', targetOrigin);
    }
  </script>
</head>
<body>hi2</body>
</html>

对我来说真正的问题是为什么你在 2020 年使用弹出窗口作为 UI,但这完全是另一回事。


推荐阅读