我正在尝试将消息从父窗口发布到它打开的子窗口。然而,该消息并未被发布。
在父窗口脚本中:
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() 会被记录,但调用的 parseMessage() 不会记录。
我已经尝试过:
更改函数的顺序。
当子窗口打开时发布消息。
例如:
var newWindow = window.open("file.html").postMessage("message string", '*');
最佳答案
您在 opener 窗口中调用 postMessage
太早了;在脚本开始在打开的窗口中执行之前。
这是一个最小的工作示例,说明您可以采取哪些措施来解决此问题。打开的窗口可以使用 window.opener.postMessage
告诉打开者何时准备好接收消息。
index.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,但这完全是另一回事。
关于javascript - postMessage() 到子窗口无法发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910623/