Examples of intra-domain and cross-domain communication between iframe child and parent page

一个新手
Release: 2023-03-15 21:38:02
Original
2482 people have browsed it

The communication between iframe subpages and parent pages has been thoroughly studied for a long time. I have never used this content before, so I didn’t study it. Today I suddenly encountered a question, so I gave it a try. Cross-domain communication uses from The source code of messenger.js provided by the Tencent team is also very simple and worth a look. The official demo is very comprehensive. Here I just give a simple example.

Intra-domain communication

Parent page

iframe子页面与父页面通信(同域)

iframe子页面与父页面同域通信

调用子页面child1.html中的sayHello()函数:

Copy after login

Sub-page

iframe子页面与父页面通信(同域)

调用父页面iframeCommunication1.html中的sayHello()函数:

Copy after login

Cross-domain communication

For IE8+ and modern browsers, cross-domain Communication mainly uses the postMessage API provided by html5 to achieve inter-domain communication. The function of postMessage is to allow programmers to send data information between two windows/frames across domains. Basically, it's like cross-domain AJAX, but instead of interacting between the browser and the server, it communicates between two clients.
For older browsers, messenger.js uses the feature that the navigator object is shared between the parent window and the iframe. The message callback function is registered on the navigator object to implement information transfer and sharing.
A very simple example is given below:

Parent page

iframe子页面与父页面通信(跨域)

iframe子页面与父页面跨域通信

向子页面child2.html发送信息:

获取信息:

        

Copy after login

Child page

iframe子页面与父页面通信(跨域)

child2

向父页面iframeCommunication2.html发送信息:


获取信息:

        

Copy after login

Reference

[1] js iframe child Communication between page and parent page
[2] Universal solution for iframe cross-domain communication - Part 2! (Ultimate solution) | Tencent AlloyTeam
[3] Messengerjs project homepagei

The above is the detailed content of Examples of intra-domain and cross-domain communication between iframe child and parent page. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!