跨文档消息通信 HTML5

使用postMessageAPI

要想接受从其他的窗口那里发过来的信息,就必须对窗口对象的message时
间进行监视,代码如下所示。
window.addEventListener("message",function(){...},false);
使用window对象的postMessage方法向其他窗口发送信息,该方法的定义
如下所示。
otherWindow.postMessage(message,targetOrigin);
该方法使用两个参数;第一个参数为所发送的消息文本,但也可以是任何
javascript对象(通过JSON转换对象为文本);第二个参数为接收信息的对象
窗口的URL地址(例如http://localhost:8080/)。可以在URL地址字符串中
使用通配符“*”指定全部地址,不过,建议使用准确的URL地址。otherWindow为要发送窗口对象的引用,可以通过window.open返回该对
象,或通过对window.iframes数组指定序号(index)或名字的方式来返回单
个iframe所属的窗口对象。
主index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跨域通信示例</title>
<script type="text/javascript">
// 监听message事件
window.addEventListener("message", function(ev) {
  	//忽略指定URL地址之外的页面传过来的消息
  	//if(ev.origin != "http://127.0.0.1:8848") {
    //	return;
  	//}
  	//显示消息
  	alert("从"+ev.origin + "那里传过来的消息:\n\"" + ev.data + "\"");
}, false);
function hello(){
	var iframe = window.frames[0];
  	//传递消息
  	iframe.postMessage("您好!", "http://127.0.0.1:8848");
}
</script>
</head>
<body>
<h1>跨域通信示例</h1>
<iframe width="400" src="http://127.0.0.1:8848/iframe.html" onload="hello()">
</iframe>
</body>
</html>

iframe.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
window.addEventListener("message", function(ev){
	if(ev.origin != "http://127.0.0.1:8848"){
		return;
	}
    document.body.innerHTML = "从"+ev.origin + "那里传来的消息。<br>\""+ ev.data + "\"";
    //向主页面发送消息
    ev.source.postMessage("珊瑚贝欢迎您!这里是" + this.location, ev.origin);
}, false);
</script>
</head>
<body></body>
</html>
微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?