我正在使用messsage
事件在浏览器窗口之间进行通信。主窗口发布到iframe,iframe与父进行通信。这个职位总是有效的。 php回声使用以下命令回复消息:
echo "<script>document.write(parent.postMessage(" . json_encode($status) . ", '*'))</script>";
有时会收到消息,有时则不然。我确信正在发送消息,因为我可以记录echo "<script>...
之后发送的状态消息。可能导致这个问题的原因是什么?
简化的javascript:
// posts login info to an iframe which logs user in
postToIframe(path, parameters, "post");
// wait for server's response
var foundMessage = false;
var messageFn = function (e) {
if (typeof e.data.status !== "undefined"){
_jsonStatus = e.data.status;
foundMessage = true;
}
window.removeEventListener("message", messageFn);
messageFn = undefined;
if (!foundMessage){
_jsonStatus = "Unknown Message: " + v(e.data);
}
};
window.addEventListener("message", messageFn, false);
var timer = new Date().getTime();
var interval = setInterval(function() {
var timer2 = new Date().getTime();
var done = true;
var message;
if (_jsonStatus.indexOf('Error') === 0){
message = _jsonStatus;
console.log(message);
done = true;
} else if (timer2 - timer > 5000){
message = 'Timeout: Failed to get report data'
console.log(message);
if (_this.status){
_this.status(message, "red");
}
done = true;
if (typeof messageFn !== undefined){
window.removeEventListener("message", messageFn);
}
} else if (_jsonStatus.substr(0, 7) == "Success"){
done = true;
} else {
// continue to wait
done = false;
}
if (done == true){
clearInterval(interval);
}
}, 1000)
简化的php:
if ($userid > 0){
$status['status'] = "Success. You are logged in.";
} else {
$status['status'] = 'Error: Login Failed';
}
echo "<script>document.write(parent.postMessage(" . json_encode($status) . ", '*'))</script>";