search
HomeWeb Front-endHTML TutorialpostMessage处理iframe 跨域问题_html/css_WEB-ITnose

背景:由于同源策略存在,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>

子页面代码

<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>

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>

子页面代码

<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>

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);        }    });

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

Statement
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
The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

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

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

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment