客户端通信的问题

鄱湖听风 2018-08-22 08:56:52
我按照疯狂js讲义安装了tomcat,但是postMessage接收不到,后来我也发到了云主机,也改了地址,但是还是没用,到底是哪里出了问题?
发送代码:
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> 跨文档发送消息 </title>
<script type="text/javascript">
var send = function()
{
// 打开一个新窗口
var targetWin = window.open('http://localhost:8888/target/target.html'
,'_blank','width=400,height=300'); // ①
// 等该窗口装载完成时,向该窗口发送消息
targetWin.onload = function ()
{
// 向http://localhost:8888/target发送消息
targetWin.postMessage(document.getElementById("msg").value
, "http://localhost:8888/target"); // ②
}
}
// 通过onmessage监听器监听其他窗口发送过来的消息
window.onmessage = function(ev)
{
// 忽略来自其他域名的跨文档消息(只接收http://localhost:8888的消息)
if (ev.origin != "http://localhost:8888")
{
return;
}
var show = document.getElementById("show");
// 显示消息
show.innerHTML += (ev.origin + "传来了消息:" + ev.data + "<br/>");
};
</script>
</head>
<body>
消息:<input type="text" id="msg" name="msg"/>
<button onclick="send();">发送消息</button>
<div id="show"></div>
</body>
</html>

接收代码:
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> 跨文档发送消息接收 </title>
<script type="text/javascript">
window.onmessage = function(ev)
{
// 忽略来自其他域名的跨文档消息(只接收http://localhost:8888的消息)
if (ev.origin != "http://localhost:8888")
{
return;
}
document.body.innerHTML = (ev.origin + "传来了消息:" + ev.data);
// 向发送该消息的页面回传消息
ev.source.postMessage("回传消息,这里是" + this.location
, ev.origin); // ①
};
</script>
</head>
<body>
</body>
</html>

按道理会是这样
但是我的是空的
...全文
103 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
NANU-NANA 2018-08-23
  • 打赏
  • 举报
回复
window 已经 open 了, 你才定义onload。
鄱湖听风 2018-08-23
  • 打赏
  • 举报
回复
引用 1 楼 u010087908 的回复:
window 已经 open 了, 你才定义onload。

我放到前面也没有用啊

87,907

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧