iframe内嵌页面双向通信

父页面

复制代码
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>父页面</title>
</head>
<body>
  <h1>父页面</h1>
  <iframe id="childIframe" src="http://child.com/child.html" width="400" height="300"></iframe>

  <script>
    // 步骤1:获取iframe的window对象(需等iframe加载完成)
    const iframe = document.getElementById('childIframe');
    let childWindow;

    // 监听iframe加载完成
    iframe.addEventListener('load', () => {
      childWindow = iframe.contentWindow;
      console.log('iframe加载完成,可通信');
    });

    // 步骤2:监听来自iframe的消息,并派发内部自定义事件
    window.addEventListener('message', (e) => {
      // 安全校验:只接收指定域名的消息(防止恶意注入)
      if (e.origin !== 'http://child.com') return;

      console.log('父页面收到iframe消息:', e.data);

      // 派发内部自定义事件,让其他逻辑响应(解耦)
      const childMsgEvent = new CustomEvent('iframe-message', {
        detail: e.data,
        bubbles: true
      });
      document.dispatchEvent(childMsgEvent);
    });

    // 步骤3:监听内部自定义事件(业务逻辑响应)
    document.addEventListener('iframe-message', (e) => {
      console.log('父页面业务逻辑响应:', e.detail);
      // 示例:更新页面内容
      document.body.insertAdjacentHTML('beforeend', `<p>收到iframe消息:${JSON.stringify(e.detail)}</p>`);
    });

    // 步骤4:向iframe发送消息(示例:点击按钮发送)
    const sendBtn = document.createElement('button');
    sendBtn.textContent = '向iframe发送消息';
    sendBtn.addEventListener('click', () => {
      if (!childWindow) return alert('iframe未加载完成');
      // 发送消息:参数1=消息内容,参数2=目标域名(*表示任意,生产环境建议指定)
      childWindow.postMessage({ type: 'parent-msg', content: '父页面的问候' }, 'http://child.com');
    });
    document.body.appendChild(sendBtn);
  </script>
</body>
</html>

子页面

复制代码
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>iframe子页面</title>
</head>
<body>
  <h2>iframe子页面</h2>

  <script>
    // 步骤1:监听来自父页面的消息,并派发内部自定义事件
    window.addEventListener('message', (e) => {
      // 安全校验:只接收父页面域名的消息
      if (e.origin !== 'http://parent.com') return;

      console.log('iframe收到父页面消息:', e.data);

      // 派发内部自定义事件,解耦业务逻辑
      const parentMsgEvent = new CustomEvent('parent-message', {
        detail: e.data,
        bubbles: true
      });
      document.dispatchEvent(parentMsgEvent);
    });

    // 步骤2:监听内部自定义事件(业务逻辑响应)
    document.addEventListener('parent-message', (e) => {
      console.log('iframe业务逻辑响应:', e.detail);
      // 示例:更新页面内容
      document.body.insertAdjacentHTML('beforeend', `<p>收到父页面消息:${JSON.stringify(e.detail)}</p>`);
    });

    // 步骤3:向父页面发送消息(示例:点击按钮发送)
    const sendBtn = document.createElement('button');
    sendBtn.textContent = '向父页面发送消息';
    sendBtn.addEventListener('click', () => {
      // window.parent 指向父页面的window对象
      window.parent.postMessage({ type: 'child-msg', content: 'iframe的回复' }, 'http://parent.com');
    });
    document.body.appendChild(sendBtn);
  </script>
</body>
</html>

nginx配置

复制代码
# Nginx 核心配置
worker_processes  1; # Windows 下建议设为1

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    # 关闭 sendfile(Windows 下兼容性更好)
    sendfile        off;
    # 连接超时配置
    keepalive_timeout  65;

    # 父页面站点配置:parent.com
    server {
        listen       80; # 监听80端口
        server_name  parent.com; # 域名匹配

        # 字符编码(防止中文乱码)
        charset utf-8;

        # 根目录:父页面所在文件夹
        root   C:\Users\user\Desktop\iframe内嵌页面通信;
        # 默认索引页(访问 parent.com 直接打开 parent.html)
        index  parent.html index.html index.htm;

        # 访问日志(可选,便于排查问题)
        access_log  logs/parent.access.log;
        error_log   logs/parent.error.log;

        # 匹配 parent.html 的访问规则
        location = /parent.html {
            try_files $uri =404; # 确保文件存在才返回
        }
    }

    # 子页面站点配置:child.com
    server {
        listen       80;
        server_name  child.com;

        charset utf-8;

        # 根目录和父页面同文件夹(因为两个html在同一目录)
        root   C:\Users\user\Desktop\iframe内嵌页面通信;
        index  child.html index.html index.htm;

        access_log  logs/child.access.log;
        error_log   logs/child.error.log;

        location = /child.html {
            try_files $uri =404;
        }
    }
}

host配置

复制代码
127.0.0.1 parent.com
127.0.0.1 child.com

链接:

https://gitee.com/xing54321/files/blob/master/iframe内嵌页面通信.zip

相关推荐
小雨下雨的雨4 小时前
井字棋AI机器人实现详解 - Minimax算法实战-鸿蒙PC Electron框架完成
前端·人工智能·算法·华为·electron·鸿蒙
ZC跨境爬虫7 小时前
跟着 MDN 学JavaScript day_7:数学运算与逻辑判断实战测试
开发语言·前端·javascript·学习·ecmascript
fangdengfu1238 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
凌云拓界8 小时前
文件管理:让AI安全操作你的电脑 ——CogitoAgent开发实战(三)
javascript·人工智能·架构·开源·node.js
凌云拓界8 小时前
联网能力:让AI看见更广阔的世界 ——CogitoAgent开发实战(四)
javascript·人工智能·架构·node.js·创业创新
JustHappy9 小时前
古法编程秘籍(六):程序到底是怎么跑起来的?从 IO 到中断,一次讲明白
前端·后端·全栈
HYCS10 小时前
用pixi.js实现fabric.js(六):从线性代数的角度理解编辑器交互
前端·javascript·canvas
卷帘依旧10 小时前
useImperativeHandle的作用
前端
卷帘依旧10 小时前
Hooks在Fiber上的存储原理
前端