搜索
首页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、不带回执信息: 
这里写图片描述

2、带回执信息: 
这里写图片描述

基本知识

首先介绍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>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>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>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>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>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尊渡假赌尊渡假赌尊渡假赌

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能