Yog*_*ort 2 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, '*');
}
Run Code Online (Sandbox Code Playgroud)
在子窗口脚本中:
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");
}
Run Code Online (Sandbox Code Playgroud)
addListeners() called已记录,但未parseMessage() called记录。
我已经尝试过:
更改函数的顺序。
当子窗口打开时发布消息。
例如:
var newWindow = window.open("file.html").postMessage("message string", '*');
Run Code Online (Sandbox Code Playgroud)
你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>
Run Code Online (Sandbox Code Playgroud)
弹出窗口.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>
Run Code Online (Sandbox Code Playgroud)
对我来说真正的问题是为什么你在 2020 年使用弹出窗口作为 UI,但这完全是另一回事。
| 归档时间: |
|
| 查看次数: |
2805 次 |
| 最近记录: |