javascript - 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
。
我已经尝试过:
改变函数的顺序。
打开子窗口时发布消息。
例如:
var newWindow = window.open("file.html").postMessage("message string", '*');
解决方案
你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,但这完全是另一回事。
推荐阅读
- python - 如何提高熊猫在列表类型列上合并的性能
- android - Android :iam 总是收到这个提示,任何人都可以解决这个问题吗?
- java - 如何格式化蓝牙便携式打印机?
- orm - 循环结构和重用EntityNew
- karate - 如何在运行时忽略空手道功能文件中的特定场景?
- angular - 找不到模块:错误:无法解析组件。尝试从使用 ng-packagr 制作的包中导入组件时遇到问题
- algorithm - 中位数算法中位数的时间复杂度
- javascript - Onclicking单选按钮显示日历以及jquery中的一个输入框
- azure - 在 Azure 云中创建多个子帐户
- jquery - 使用 jQuery 根据 JoinOn 日期禁用/限制 LeaveOn 日期