我正在努力使两个网站之间的数据交换系统在他们的客户端。为此,我使用EasyXDM。(http://easyxdm.net/)。这是我的父网站代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>EasyXDM Test</title>
<script type="text/javascript" src="easyXDM.debug.js"></script>
<script type="text/javascript">
var serv_socket = new easyXDM.Socket({
remote: "http://localhost:39452/EasyXDM/Default.aspx",
onMessage: function (message, origin) {
document.getElementById('msg').innerText="Received '" + message + "' from '" + origin + "'";
},
onReady: function () {
serv_socket.postMessage("ID");
}
});
</script>
</head>
<body>
<form id="form1">
<div>
<iframe src="http://localhost:39452/EasyXDM/Default.aspx"></iframe>
<input type="text" id="msgtext" /><a href="#" onclick="serv_socket.postMessage('d')">Send message</a>
<div id="msg"></div>
</div>
</form>
</body>
</html>
下面是位于localhost:39452
域名的子网站代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Server</title>
</head>
<body>
<form id="form1">
<input type="text" id="msgtext" />
<div>
<script type="text/javascript" src="easyXDM.debug.js"></script>
<script type="text/javascript">
var socket = new easyXDM.Socket({
onMessage: function (message, origin) {
//document.getElementById('msg').innerText="Received '" + message + "' from '" + origin + "'";
socket.postMessage(message);
},
onReady: function (msg) {
socket.postMessage(msg);
}
});
function send() {
socket.postMessage('this is message from server');
}
</script>
<a href="#" id="sender" onclick="send()">Send message</a>
</div>
</form>
</body>
</html>
问题是,当我在儿童网站上点击Send message
并调用socket.postMessage()
时,它说Uncaught TypeError: Cannot read property 'postMessage' of undefined.
。请告诉我如何解决这个问题?
Update: socket
变为null或undefined .
我终于找到了解决方案:https://stackoverflow.com/a/13122604/1576363。我从父端删除了iframe
,并将套接字的container
属性添加到div
的id
中,它起作用了。这样做的原因是EasyXDM代码会自动将iframe
添加到文档中。如果您添加iframe
与URL的孩子,你会得到这个错误。从链接的答案中,有一个清晰的解释:
"消费者"是父文档,EasyXDM加载"provider"是子iframe。