• js 不同域iframe 与父页面消息通信


    var iframe = document.getElementById("myIframe");
    var iframeWindow = iframe.contentWindow;
    
    • 1
    • 2

    💡访问 iframe 页面中的方法

    iframeWindow.methodName();
    
    • 1

    其中,methodName 为 iframe 页面中定义的方法名。需要注意的是,父页面和 iframe 页面必须同源(即协议、域名和端口号相同)才能访问彼此的方法。如果两个页面不同源,则会出现跨域问题,无法相互访问。

    💡跨文本消息

    跨文档消息(Cross-document Messaging):使用postMessage API,在父页面和iframe之间进行消息通信。这样可以安全地在不同域之间传递数据,但需要在父页面和iframe中编写消息监听和处理的逻辑。

    监听消息

    💡在父页面中添加消息监听器,监听来自iframe的消息:

    window.addEventListener("message", function(event) {  
      // 判断消息来源是否为iframe  
      if (event.source !== iframe.contentWindow) {  
        return;  
      }  
        
      // 处理接收到的消息  
      console.log(event.data);  
    }, false);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    💡在iframe页面中添加消息监听器,监听来自父页面的消息:

    window.addEventListener("message", function(event) {  
      // 判断消息来源是否为父页面  
      if (event.source !== parent.window) {  
        return;  
      }  
        
      // 处理接收到的消息  
      console.log(event.data);  
    }, false);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    发送消息

    💡在父页面中向iframe发送消息

    iframe.contentWindow.postMessage("Hello, iframe!", "https://example.com");
    
    • 1

    💡在iframe页面中向父页面发送消息

    parent.window.postMessage("Hello, parent!", "https://example.com");
    
    • 1

    其中,postMessage方法的第一个参数为要发送的消息,第二个参数为接收消息的域(目标页面的window.location.href),用于验证消息来源的安全性。需要注意的是,在使用postMessage进行消息通信时,需要确保父页面和iframe的通信协议和消息格式的定义一致,以避免出现通信失败或数据解析错误等问题。

  • 相关阅读:
    Windows安装docker
    图论岛屿问题DFS+BFS
    Android使用setXfermode例子
    【自律】如何长期自律-迎难而上
    网卡限速工具之WonderShaper
    Vue:生命周期(从出生到销毁)
    Unity 3D视频教程
    DMRS的产生
    openvpn组网技术原理及配置过程(centos服务器/安卓客户端/linux客户端)
    C++ day 3
  • 原文地址:https://blog.csdn.net/qq_26318597/article/details/132900427