本文介紹了詳解html5 postMessage解決跨域通訊的問題,分享給大家,具體如下:
效果圖
postmessage解析HTML5提供了新型機制PostMessage實作安全的跨源通訊.語法otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow: 其他視窗的一個引用, 例如IFRAME的contentWindow屬性, 執行,window.open傳回的視窗物件. message: 將要傳送到其他視窗的資料. targetOrigin:透過視窗的origin屬性來指定哪些視窗能接收到訊息事件, 其值可以是字元*(表示無限制)或一個URL transfer:是一串和message同時傳遞的Transferable物件.這些物件的所有權將被轉移給訊息的接收方, 而發送一放將不再保有所有權.element.addEventListener(event,fn,useCaption ); 三個參數event 事件例如click mouseenter mouseleave 回調函數useCaption用於描述是冒泡還是捕獲。預設值是false,即冒泡傳遞。 當值為true,就是捕獲傳遞。實現方式
主介面main.html
<!DOCTYPE html><html lang=en><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>跨域資料存取</title> <script type=text/javascript> window.addEventListener('message',function(e){ console.log(e--->,e); const data = e.data; document.getElementById('main1').style.backgroundColor=e.data; },false) </script></head><body> <div id=main1 style=width:200px;height:200px;margin:100px;border:solid 1px #000;> 我是主介面,等待接收iframe的傳遞</div> <div style=margin:100px;> iframe <iframe src=iframe src= http://localhost:3000/iframe.html width=800px height=300px ></iframe> </div></body></html>
iframe介面
<!DOCTYPE html><html lang=en><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> <style type=text/css> html,body{ height:100%; margin:0px; } </style></head> <body style=height:100%;> <div id=frame style=height:200px; width:200px;background-color:rgb(204 , 204, 0) onclick=changeColor()> 點選改變顏色</div> <script type=text/javascript> function changeColor(){ var frame = document.getElementById('frame'); var color=frame.style.backgroundColor; if(color=='rgb(204, 102, 0)'){ color='rgb(204, 204, 0)'; }else{ color='rgb(204,102,0)'; } console.log(frame===>,frame); console.log(color,color); frame.style.backgroundColor=color; window.parent.postMessage(color, '*'); } </script> </body></html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。