A:端口3000
import React, { useEffect } from 'react';function App() {useEffect(() => {const childWindow = document.getElementById('child').contentWindow;const sendMessageToChild = () => {childWindow.postMessage("主页面消息", "http://localhost:4000");};const receiveMessageFromChild = (event) => {if (event.origin === "http://localhost:4000" && typeof event.data === "string") {console.log(event);const messageElement = document.getElementById('message');if (messageElement) {messageElement.innerHTML = `收到 ${event.origin} 消息:${event.data}`;}event.source.postMessage("主页面收到消息并回复", event.origin);}};window.addEventListener('message', receiveMessageFromChild, false);sendMessageToChild();return () => {window.removeEventListener('message', receiveMessageFromChild);};}, []);return (<div className="App"><iframe id="child" src="http://localhost:4000"></iframe><div><h2>主页面跨域接收消息区域</h2><div id="message"></div></div></div>);
}export default App;
B:端口4000
import React, { useEffect } from 'react';function App() {useEffect(() => {const parentWindow = window.parent;const sendMessageToParent = () => {parentWindow.postMessage("子页面消息收到", 'http://localhost:3000');};const receiveMessageFromParent = (event) => {if (event.origin === "http://localhost:3000" && typeof event.data === "string") {console.log(event);const messageElement = document.getElementById('message');if (messageElement) {messageElement.innerHTML = `收到 ${event.origin} 消息:${event.data}`;}event.source.postMessage("子页面收到消息并回复", event.origin);}};window.addEventListener('message', receiveMessageFromParent, false);sendMessageToParent();return () => {window.removeEventListener('message', receiveMessageFromParent);};}, []);return (<div className="App">hello world<div id="message"></div></div>);
}export default App;