---
title: "跨文档消息传递应用"
author: "cakin24"
date: "2017-04-27T21:11:03Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2017-04-27T21:11:03Z"
id: 2371548
url: "https://cakin24.iteye.com/blog/2371548"
---

**一 应用**

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 onclick="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>
```

 

**三 运行结果**

![](http://dl2.iteye.com/upload/attachment/0124/6001/cad15a9d-d005-3814-94a6-6138238d5cef.png)