标签:
服务器上页面之间 使用js 传递信息
信息发送页 index.html:
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="utf-8" /> 6 <title></title> 7 </head> 8 9 <body> 10 <input type="text" name="msg" id="msg" value="" /> 11 <button onclick="send()">send</button> 12 <div id="show"> 13 14 </div> 15 <!-- 16 17 18 描述: 跨文档通信,相应不安全 19 --> 20 <script type="text/javascript"> 21 /* 每次构造新的 window, 只向 新 构造的 窗体 发送信息,可能是因为覆盖的关系,旧的窗体的不到消息*/ 22 var targetWin; 23 var send = function() { 24 //var targetWin = new window(‘http://127.0.0.1:8020/PostMessage/demo.html‘ ); 25 /*依然是重新打开 重新构造,只向新窗口传递信息*/ 26 targetWin = window.open(‘http://127.0.0.1:8020/PostMessage/demo.html‘, ‘_blank‘, ‘width=400,height=300‘); 27 targetWin.onload = function() { 28 targetWin.postMessage(document.getElementById(‘msg‘).value, ‘http://127.0.0.1:8020/PostMessage‘); 29 } 30 } 31 window.onmessage = function(event) { 32 if (event.origin != ‘http://127.0.0.1:8020‘) { 33 return; 34 } 35 var show = document.getElementById(‘show‘); 36 show.innerHTML += (event.origin + ‘传来了 消息:‘ + event.data + ‘<br/>‘); 37 } 38 </script> 39 40 </body> 41 42 </html>
信息接收页 demo.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <script type="text/javascript"> 9 window.onmessage = function (event) 10 { 11 if(event.origin != ‘http://127.0.0.1:8020‘){ 12 return; 13 } 14 document.body.innerHTML = (event.origin +‘传来了消息:‘+ event.data); 15 event.source.postMessage(‘回传消息,这里是‘+this.location,event.origin); 16 } 17 </script> 18 </body> 19 </html>
标签:
原文地址:http://www.cnblogs.com/ChuangZhang/p/5406338.html