效果
如何运行
父页面代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><h1>父亲-页面</h1><iframe src="./b.html" width="500" height="300" id="topNav"></iframe><script>function parentEvent(a) {alert("父亲被儿子调用"+JSON.stringify(a));}// 监听消息window.addEventListener("message", receiveMessage, false);function receiveMessage(event) {debuggerif (event.data.event_id === "my_cors_message") {console.log('event.data',event.data);parentEvent(event.data); // 触发父页面事件}}// 参考https://cloud.tencent.com/developer/ask/sof/101133167// 原文链接:https://blog.csdn.net/mkmmkkghhhhhhhh/article/details/131370510</script>
</body></html>
子页面代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><h2>我是儿子页面--kkk</h2><button onclick="triggerParentEvent()">方法1:调用父亲页面</button><script>function triggerParentEvent() {debuggerconst parentWindow = window.parent;parentWindow.postMessage({event_id: 'my_cors_message',data: { // 这里可以传递多个参数给父页面v1: 'value1',v2: 'value2'}},['http://localhost:80','http://localhost:89'] // 这里填入域名,能指定给哪个网址发送信息); // 发送消息}</script>
</body>
</html>