
HTML5提供了新型機(jī)制PostMessage實(shí)現(xiàn)安全的跨源通信. 語法
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow: 其他窗口的一個(gè)引用, 比如IFRAME的contentWindow屬性, 執(zhí)行,
window.open返回的窗口對象. message: 將要發(fā)送到其他窗口的數(shù)據(jù). targetOrigin:
通過窗口的origin屬性來指定哪些窗口能接收到消息事件, 其值可以是字符”*”(表示無限制)或者一個(gè)URL transfer:
是一串和message同時(shí)傳遞的Transferable對象. 這些對象的所有權(quán)將被轉(zhuǎn)移給消息的接收方, 而發(fā)送一放將不再保有所有權(quán).
element.addEventListener(event,fn,useCaption ); 三個(gè)參數(shù) event 事件 比如
click mouseenter mouseleave 回調(diào)函數(shù) useCaption
用于描述是冒泡還是捕獲。默認(rèn)值是false,即冒泡傳遞。 當(dāng)值為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 跨域數(shù)據(jù)訪問 /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 p id= main1 >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 >相關(guān)推薦:
postMessage處理iframe 跨域問題_html/css_WEB-ITnose
H5中怎樣使用postMessage實(shí)現(xiàn)兩個(gè)網(wǎng)頁間傳遞數(shù)據(jù)
以上就是html5新機(jī)制:postMessage實(shí)現(xiàn)安全跨域通信(代碼)的詳細(xì)內(nèi)容,其它編程語言
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時(shí)間聯(lián)系我們修改或刪除,多謝。
新聞熱點(diǎn)
疑難解答
圖片精選