Table of Contents
一:传统的解决方式。
二:html5 postMessage的产生
三:iframe获取父页面信息
父页面代码
子页面代码
四:iframe传递信息给父页面
五:postmessage简单分析和安全问题
Home Web Front-end HTML Tutorial postMessage处理iframe 跨域问题_html/css_WEB-ITnose

postMessage处理iframe 跨域问题_html/css_WEB-ITnose

Jun 24, 2016 am 11:25 AM

背景:由于同源策略存在,javascript的跨域一直都是一个棘手的问题。 父页面无法直接获取iframe内部的跨域资源;同时,iframe内部的跨域资源也无法将信息直接传递给父页面 。

一:传统的解决方式。

传统的iframe资源解决方式:主要通过通过中间页面代理,此处不再赘述,参考 中间页获取跨域iframe

二:html5 postMessage的产生

随着HTML5的发展,html5工作组提供了两个重要的接口: postMessage(send) 和 onmessage 。这两个接口有点类似于websocket,可以实现两个跨域站点页面之间的数据传递。

postMessage API

下面是实践过程中两个小栗子:分别父页面传递信息给iframe,iframe传递信息给父页面。

三:iframe获取父页面信息

话不多说,直接上码:

参考demo: 父页面传给子页面demo

父页面代码

<html><head>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    <title>崔涣 iframe postmessage 父页面</title>    <script type="text/JavaScript">        function sendIt() {            // 通过 postMessage 向子窗口发送数据            document.getElementById("otherPage").contentWindow                    .postMessage(                    document.getElementById("message").value,                    "http://cuihuan.net:8003"            );        }    </script></head><body><!-- 通过 iframe 嵌入子页面 --><iframe src="http://cuihuan.net:8003/test.html" id="otherPage"></iframe><br/><br/><input type="text" id="message"/><input type="button" value="Send to child.com" onclick="sendIt()"/></body></html>
Copy after login

子页面代码

<html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  <title>崔涣测试子页面信息</title>  <script type="text/JavaScript">      //event 参数中有 data 属性,就是父窗口发送过来的数据     window.addEventListener("message", function( event ) {          // 把父窗口发送过来的数据显示在子窗口中       document.getElementById("content").innerHTML+=event.data+"<br/>";      }, false );  </script>  </head>  <body>      this is the 8003 port for cuixiaozhuai      <div id="content"></div>  </body>  </html>
Copy after login

demo 效果如下图:两个跨域页面之间,父页面给子页面传递数据。

四:iframe传递信息给父页面

参考demo: 跨域子页面传给父页面demo

父页面代码

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>崔涣测试父页面</title> <script type="text/JavaScript">     //event 参数中有 data 属性,就是父窗口发送过来的数据     window.addEventListener("message", function( event ) {         // 把父窗口发送过来的数据显示在子窗口中       document.getElementById("content").innerHTML+=event.data+"<br/>";     }, false ); </script> </head> <body>     <iframe src="http://cuihuan.net:8003/iframeSon.html" id="otherPage"></iframe>     <br/>     this is the 1015 port for cuixiaozhuai。     <div id="content"></div> </body> </html>
Copy after login

子页面代码

<html><head>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    <title>崔小涣iframe postmessage 测试页面</title>    <script type="text/JavaScript">        function sendIt() {            // 子页面给父页面传输信息             parent.postMessage(                document.getElementById("message").value,                "http://cuihuan.net:1015"            );        }    </script></head><body><br/>this is the  port for cuixiaozhuai<input type="text" id="message"/><input type="button" value="Send to child.com" onclick="sendIt()"/></body></html>
Copy after login

demo 效果如下图:两个跨域页面之间,子页面传递数据给父页面传递数据。

五:postmessage简单分析和安全问题

postmessage 传送过来的信息如下图,

几乎包含了所有应该有的信息。甚至data中可以包含object,出于安全考虑可以域的校验,数据规则的校验安全校验,如下代码

 window.addEventListener('message', function (event) {                //校验函数是否合法        var checkMessage = function () {            // 只获取需要的域,并非所有都可以跨域            if (event.origin != "need domain") {                return false;            }                        var message = event.data;            // 传输数据类型校验            if (typeof(message) !== 'object') {                return false;            }            // message 的rule中包含xxx则为xxx需要字段。            return message.rule === "xxx";        };        if (checkMessage()) {            // 通过校验进行相关操作            addDetailFunc(event);        }    });
Copy after login

【转载请注明: postMessage处理iframe 跨域问题 | 靠谱崔小拽 】

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

See all articles