html5 JS跨域通信

来源:互联网 发布:国外旅游景点推荐 知乎 编辑:程序博客网 时间:2024/06/01 07:11

主页面:http://ext.js.com

跨域:http://hb.test.com

<!DOCTYPE html><html><head><meta charset="utf-8"><title>跨域通信示例</title><script type="text/javascript">window.addEventListener("message",function(ev){if(ev.origin != "http://hb.test.com"){return;}document.getElementById("h").innerHTML = "从"+ev.origin + "那里传过来的消息:\n" + ev.data ;},false);function hello(){var iframe= window.frames[0];iframe.postMessage("你好","http://hb.test.com");}</script></head><body><h1>跨域通信</h1><iframe width="400" src="http://hb.test.com/a1.html" onload="hello()"></iframe><div id="h"></div></body></html>

iframe页面

<!DOCTYPE html><html><head><meta charset="utf-8"><title>跨域通信示例</title><script type="text/javascript">window.addEventListener("message",function(ev){if(ev.origin != "http://ext.js.com"){return;}document.body.innerHTML="从"+ev.origin + "那里传来的消息。<br />" + ev.data ;ev.source.postMessage("您好,这里是"+this.location, ev.origin);},false);</script></head><body></body></html>



原创粉丝点击