跨文档消息传递应用

 

一 应用
source.html程序调用window的open方法打开一个新的窗口,接下来程序即可调用新窗口对应的window对象的postMessage向该文档发送消息。
 
 
二 代码
1、source.html
<!DOCTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> 跨文档发送消息 </title>
	<script type="text/javascript">
	var send = function() 
	{
		// 打开一个新窗口
		var targetWin = window.open('http://localhost/test1/1/target/target.html'
			,'_blank','width=400,height=300');    //①
		// 等该窗口装载完成时,向该窗口发送消息
		targetWin.onload = function ()
		{ 
			// 向http://localhost:8888/target发送消息
			targetWin.postMessage(document.getElementById("msg").value
				, "http://localhost/test1/1/target");    //②
		}
	}
	// 通过onmessage监听器监听其他窗口发送回来的消息
	window.onmessage = function(ev) 
	{
		// 忽略来自其他域名的跨文档消息(只接受http://localhost的消息)
		if (ev.origin != "http://localhost") 
		{
			return;
		}
		var show = document.getElementById("show");
		// 显示消息
		show.innerHTML += (ev.origin + "传来了消息:" + ev.data + "<br/>");
	};
	</script>
</head>
<body>
	消息:<input type="text" id="msg" name="msg"/>
	<button οnclick="send();">发送消息</button>
	<div id="show"></div>
</body>
</html>
 
2、target.html
<!DO
CTYPE html>
<html>
<head>
	<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
	<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	<title> 跨文档发送消息接收 </title>
	<script type="text/javascript">
		window.onmessage = function(ev) 
		{
			// 忽略来自其他域名的跨文档消息(只接受http://localhost:8888的消息)
			if (ev.origin != "http://localhost") 
			{
				return;
			}
			document.body.innerHTML = (ev.origin + "传来了消息:" + ev.data);
			// 向发送该消息的页面回传消息
			ev.source.postMessage("回传消息,这里是" + this.location
				, ev.origin);    //①
		};
	</script>
</head>
<body>
</body>
</html>
 
三 运行结果


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值