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
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

How to efficiently add stroke effects to PNG images on web pages?How to efficiently add stroke effects to PNG images on web pages?Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

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 <datalist> 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 <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

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 <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),