html5的跨域处理
这篇代码是我在一个技术博客中看到的,介绍的很细致。代码摘过来,自己可以常看看。
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> 5 <title>cross-domain demo by js8.in</title> 6 </head> 7 <body> 8 <div style="width:100%;border:2px solid green;"> 9 10 <h3>this page from :<span id="host"></span></h3> 11 <input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button> 12 13 <div id="log"> 14 <p><b>这里是收到的消息</b></p> 15 </div> 16 <iframe id="iframeA" src="http://4.qdemo.sinaapp.com/xdomain/postmessage/proxy.html" style="margin:10px;border:2px solid #ff6600;width:90%;height:400px;"></iframe> 17 </div> 18 <script type="text/javascript"> 19 document.getElementById('host').innerHTML = location.host; 20 function send(){ 21 var val = document.getElementById('data').value; 22 sendMessage(val); 23 } 24 (function(win, doc){ 25 var ifr = doc.getElementById('iframeA').contentWindow; 26 var cb = function(json){ 27 var p = document.createElement('p'); 28 p.innerHTML = (new Date).toLocaleTimeString()+'收到消息:'+json; 29 document.getElementById('log').appendChild(p); 30 }; 31 var sendMessage = function(){ 32 if(win.postMessage){ 33 if (win.addEventListener) { 34 win.addEventListener("message",function(e){ 35 cb.call(win,e.data); 36 },false); 37 }else if(win.attachEvent) { 38 win.attachEvent("onmessage",function(e){ 39 cb.call(win,e.data); 40 }); 41 } 42 return function(data){ 43 ifr.postMessage(data,'*'); 44 }; 45 }else{ 46 var hash = ''; 47 48 setInterval(function(){ 49 50 if (win.name !== hash) { 51 hash = win.name; 52 cb.call(win, hash); 53 } 54 }, 50); 55 return function(data){ 56 ifr.name = data; 57 }; 58 } 59 }; 60 win.sendMessage = sendMessage(); 61 })(window, document); 62 63 64 65 </script> 66 </body> 67 </html>
主要是其中的js部分,为了好理解,html我也拿过来了~~