跨文档信息传递
跨文档信息传送,指的是在来自不同域的页面间传递消息
例如 :www.wrox.com域中的页面与位于一个内嵌框架中的p2p.wrox.com域中的页面通信
postMessage()
XDM的核心方法是postMessage(),
它的主要目的是向另一个地方传递数据,另一个地方指的是包含在当前页面中的<iframe>元素,或者由当前页面弹出的窗口。
接收2个参数:
<1>一条消息,
<2>一个表示信息接收方来自哪个域的字符串。不推荐使用*
第二个参数对保障安全通信非常重要,可以防止浏览器把消息发送到不安全的地方
常可以用作跨域绕过同源策略
同源策略
同源策略:只有域,端口,协议相同的URL才能够相互通信
案例图片:从内嵌框架中向外部发送信息
2个分别来自不同的源
内嵌:http://test.suanliutudousi.com/test/demo/send.html
外部:http://www.suanliutudousi.com/TestInstance/receive.html
想要体验一下?戳这里==>输入数据后打开控制台即可看到信息。 http://www.suanliutudousi.com/TestInstance/receive.html
如果不能运行的话,你可以将对应的地址换成本地的不同的源即可。
send.html
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <textarea name="" rows="" cols="" id="text"></textarea> <button>发送</button> <script type="text/javascript"> var btn = document.getElementsByTagName("button")[0]; btn.onclick = function() { /** * 向接收页面发送消息, * otherWindow.postMessage(message, targetOrigin, [transfer]); * targetOrigin用*不安全 * top对象始终指向最高层的框架,也就是浏览器窗口 * window对象指向的是当前所在框架的特定实例 */ top.postMessage(document.getElementById("text").value, "http://www.suanliutudousi.com"); //这里的top指向浏览器窗口,用window会报Failed to execute 'postMessage' on 'DOMWindow' }; //处理接收回执信息 window.onmessage = function(event) { event = window.event || event; if(event.origin == "http://www.suanliutudousi.com") { console.log(event.data); } }; //接收回执信息 </script> </body> </html>
receive.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>跨域POST消息发送</title> </head> <body> <iframe src="http://test.suanliutudousi.com/test/demo/send.html" id="otherPage"></iframe> <script type="text/javascript"> //处理内嵌框架发过来的信息,接收到XDM消息时,会触发window对象的message事件 window.onmessage = function(event) { /** * window.onmessage事件是以异步形式触发的,触发后,event事件对象将包含3个属性 * @data:作为postMessage()第一个参数传入的字符串数据 * @origin:发送消息的文档所在的域, * @source,发送消息的文档的window对象的代理:event.source相当于发送方中的window对象 */ event = window.event || event; if(event.origin == "http://test.suanliutudousi.com") { //结尾不能有/ //如果发送方来自http://test.suanliutudousi.com,验证来源,保证安全。 console.log(event.data); //输出接收到的信息 event.source.postMessage("received", "http://test.suanliutudousi.com"); //向发送方返回回执信息 } }; </script> </body> </html>