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.
<!DOCTYPE html><html><head><title>iframe子页面与父页面通信(同域)</title><meta charset="utf-8"><script type="text/javascript"> function sayHello(){ alert("iframeCommunication1.html"); } function say(){ child1.window.sayHello(); child1.window.document.getElementById("button_c").value = "the call is complete"; }</script></head><body><h1>iframe子页面与父页面同域通信</h1>调用子页面child1.html中的sayHello()函数:<input type="button" id="button_p" name="hello" value="call" onclick="say()"><br><br><iframe src="child1.html" id="child1"></iframe></body></html>
<!DOCTYPE html><html><head><title>iframe子页面与父页面通信(同域)</title><meta charset="utf-8"><script type="text/javascript"> function sayHello(){ alert("child.html"); } function say(){ parent.sayHello(); parent.window.document.getElementById("button_p").value = "the call is complete"; }</script></head><body><p>调用父页面iframeCommunication1.html中的sayHello()函数:</p><input type="button" id="button_c" name="hello" value="call" onclick="say()"></body></html>
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:
<!DOCTYPE html><html><head><title>iframe子页面与父页面通信(跨域)</title><meta charset="utf-8"><script src="js/messenger.js"></script></head><body><h1>iframe子页面与父页面跨域通信</h1>向子页面child2.html发送信息:<input type="button" id="button_p" value="call" onclick="sendMessage('child2')"><br><br>获取信息:<pre id="output">