搜尋
首頁web前端H5教程HTML5中postMessage實作跨網域的程式碼分析

這篇文章帶給大家的內容是關於HTML5中postMessage實現跨域的程式碼分析,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

對於使用H5實作跨域,很多人都一直處於半懂狀態。知道使用postMessage發送訊息,使用onMessage接受訊息,但是到底哪個方法應該用window呼叫哪個應該用iframe的contentWindow呼叫不是很清楚。下面是我做的一個本地實作跨域的小demo,可以在github下載這個範例。為了執行它,首先,你需要找到你電腦的hosts文件,在127.0.0.1 localhost下添加如下程式碼:

127.0.0.1   localhost
127.0.0.1   main.com
127.0.0.1   A.com
127.0.0.1   B.com

然後,你需要啟動一個伺服器,例如Apache等,把github上下載的三個html檔案放到你的伺服器。最後,你只需訪問http://main.com:你的連接埠號碼 ,就可以進行跨域通訊了。 

三個html檔案的關係如下:三個網域:http://main.com:8090 ; http://a.com:8090 ; http://b.com:8090 。 主頁面maindomain.html在main.com,兩個iframe (subAdomain.html , subBdomain.html)分別在 a.com , b.com 。在maindomain.html中,向textarea輸入訊息,點選send to iframe按鈕,可以傳送訊息到指定iframe (subAdomain.html 或subBdomain.html),在ifame中也可以傳送訊息到maindomain.html,同時,有一個收到ifame訊息的回執訊息。

這應該是很常見的場景,把網站公共的資源放到某個子網域,在其他子網域需要存取該子網域上的資源。實現的效果如下。

1、不帶回執訊息: 
HTML5中postMessage實作跨網域的程式碼分析

2、帶回執訊息: 
HTML5中postMessage實作跨網域的程式碼分析





##基本知識

    首先介紹onMessage事件中,event的一些屬性,理解這些可以使你很容易讀懂我的範例。
  • * data: 傳入的資料 

    * origin: 傳送訊息的文件所在的網域 

    * source: 傳送訊息的文件的window物件的代理 
  • 如果你想在子網域X向子網域Y傳送訊息,你需要,在子網域X的html文件,取得Y的window物件(iframe的contentWindow),然後呼叫postMessage(message, Y所在的域),同時,在子域Y的html檔中,監聽window物件message事件(使用onMessage)就好。當然,你可以在onMessage中再次使用postMessage,傳送一個回執訊息給子網域X。 我們常常混亂的是,在哪個域的window物件上呼叫postMessage。

程式碼

main.com

    <h1 id="This-nbsp-is-nbsp-the-nbsp-main-nbsp-domain">This is the main domain</h1>
    <div style="margin:0 20px;">
        <textarea name="main" cols="80" rows="5"></textarea><br/>
        <input type="button" value="send to iframe A"/>
        <input type="button" value="send to iframe B"/>
    </div>
    <div style="float:left; margin:0 20px;">
        <h3 id="iframe-nbsp-A">iframe A</h3>
        <iframe src="http://a.com:8090/subAdomain.html" frameborder="1" style="width:300px; height:300px;"></iframe>
    </div>
    <div style="float:left;">
        <h3 id="iframe-nbsp-B">iframe B</h3>
        <iframe src="http://b.com:8090/subBdomain.html" frameborder="1" style="width:300px; height:300px;"></iframe>
    </div>
    <div style="float:left;">
        <h5 id="received"></h5>
    </div>
    <script>
        var received = document.querySelector(&#39;#received&#39;);
        var sendToIframeA = document.querySelectorAll(&#39;input&#39;)[0];
        var sendToIframeB = document.querySelectorAll(&#39;input&#39;)[1];
        var iframeA = document.querySelectorAll(&#39;iframe&#39;)[0];
        var iframeB = document.querySelectorAll(&#39;iframe&#39;)[1];
 
        //receive message
        function getMessage(e){
            console.log(&#39;main received!&#39;);
            received.innerHTML = &#39;Receive message from &#39; + e.origin + &#39;, the data is &#39; + e.data;
            e.source.postMessage(&#39;Received the message&#39;, e.origin);
        }
        window.addEventListener(&#39;message&#39;, getMessage, false);
 
        //post message
        sendToIframeA.addEventListener(&#39;click&#39;, function(){
            var content = document.querySelector(&#39;textarea&#39;).value;
            iframeA.contentWindow.postMessage(content, &#39;http://a.com:8090&#39;);
        }, false);
        sendToIframeB.addEventListener(&#39;click&#39;, function(){
            var content = document.querySelector(&#39;textarea&#39;).value;
            iframeB.contentWindow.postMessage(content, &#39;http://b.com:8090&#39;);
        }, false);
    </script>

a.com

       <h5 id="This-nbsp-is-nbsp-domain-nbsp-A">This is domain A</h5>
    <textarea name="subA" cols="30" rows="10"></textarea>
    <input type="button" value="send to parent"/>
    <div style="float:left;">
        <h5 id="received"></h5>
    </div>
    <script>
        var send = document.querySelector(&#39;input&#39;);
        var text = document.querySelector(&#39;textarea&#39;);
        var received = document.querySelector(&#39;#received&#39;);
 
        //receive message
        function getMessage(e){
            console.log(&#39;A received!&#39;);
            received.innerHTML = &#39;Receive message from &#39; + e.origin + &#39;, the data is &#39; + e.data;
            //e.source.postMessage(&#39;Received the message&#39;, e.origin);
        }
        window.addEventListener(&#39;message&#39;, getMessage, false);
 
        //post message
        send.addEventListener(&#39;click&#39;, function(){
            var content = text.value;
            window.parent.postMessage(content, &#39;http://main.com:8090&#39;);
        }, false);
    </script>
b.com

    <h5 id="This-nbsp-is-nbsp-domain-nbsp-B">This is domain B</h5>
    <textarea name="subB" cols="30" rows="10"></textarea>
    <input type="button" value="send to parent"/>
    <div style="float:left;">
        <h5 id="received"></h5>
    </div>
    <script>
        var send = document.querySelector(&#39;input&#39;);
        var text = document.querySelector(&#39;textarea&#39;);
        var received = document.querySelector(&#39;#received&#39;);
 
        //receive message
        function getMessage(e){
            console.log(&#39;B received!&#39;);
            received.innerHTML = &#39;Receive message from &#39; + e.origin + &#39;, the data is &#39; + e.data;
            //e.source.postMessage(&#39;Received the message&#39;, e.origin);
        }
        window.addEventListener(&#39;message&#39;, getMessage, false);
 
        //post message
        send.addEventListener(&#39;click&#39;, function(){
            var content = text.value;
            window.parent.postMessage(content, &#39;http://main.com:8090&#39;);
        }, false);
    </script>

相關文章推薦:

HTML5應用程式:離線的應用程式以及儲存的應用程式############HTML5 canvas實作中獎轉盤的實例程式碼## ##########Html5中postmessage實作子父視窗傳值的程式碼#######

以上是HTML5中postMessage實作跨網域的程式碼分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
H5:網絡標準和技術的發展H5:網絡標準和技術的發展Apr 15, 2025 am 12:12 AM

Web标准和技术从HTML4、CSS2和简单的JavaScript演变至今,经历了显著的发展。1)HTML5引入了Canvas、WebStorage等API,增强了Web应用的复杂性和互动性。2)CSS3增加了动画和过渡功能,使页面效果更加丰富。3)JavaScript通过Node.js和ES6的现代化语法,如箭头函数和类,提升了开发效率和代码可读性,这些变化推动了Web应用的性能优化和最佳实践的发展。

H5是HTML5的速記嗎?探索細節H5是HTML5的速記嗎?探索細節Apr 14, 2025 am 12:05 AM

H5不僅僅是HTML5的簡稱,它代表了一個更廣泛的現代網頁開發技術生態:1.H5包括HTML5、CSS3、JavaScript及相關API和技術;2.它提供更豐富、互動、流暢的用戶體驗,能在多設備上無縫運行;3.使用H5技術棧可以創建響應式網頁和復雜交互功能。

H5和HTML5:網絡開發中常用的術語H5和HTML5:網絡開發中常用的術語Apr 13, 2025 am 12:01 AM

H5與HTML5指的是同一個東西,即HTML5。 HTML5是HTML的第五個版本,帶來了語義化標籤、多媒體支持、畫布與圖形、離線存儲與本地存儲等新功能,提升了網頁的表現力和交互性。

H5指的是什麼?探索上下文H5指的是什麼?探索上下文Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5:工具,框架和最佳實踐H5:工具,框架和最佳實踐Apr 11, 2025 am 12:11 AM

H5開發需要掌握的工具和框架包括Vue.js、React和Webpack。 1.Vue.js適用於構建用戶界面,支持組件化開發。 2.React通過虛擬DOM優化頁面渲染,適合複雜應用。 3.Webpack用於模塊打包,優化資源加載。

HTML5的遺產:當前了解H5HTML5的遺產:當前了解H5Apr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5代碼:可訪問性和語義HTMLH5代碼:可訪問性和語義HTMLApr 09, 2025 am 12:05 AM

H5通過語義化元素和ARIA屬性提升網頁的可訪問性和SEO效果。 1.使用、、等元素組織內容結構,提高SEO。 2.ARIA屬性如aria-label增強可訪問性,輔助技術用戶可順利使用網頁。

H5與HTML5相同嗎?H5與HTML5相同嗎?Apr 08, 2025 am 12:16 AM

"h5"和"HTML5"在大多數情況下是相同的,但它們在某些特定場景下可能有不同的含義。 1."HTML5"是W3C定義的標準,包含新標籤和API。 2."h5"通常是HTML5的簡稱,但在移動開發中可能指基於HTML5的框架。理解這些區別有助於在項目中準確使用這些術語。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器