首页 > 解决方案 > 在我的页面和 iframe 之间进行通信并相互发送数据

问题描述

我正在尝试在我的页面和另一个 iframe 之间进行通信,这是另一个页面,我有,

在我的 iframe 页面上,我在头部插入了这个脚本

if(typeof window !== 'undefined'){
 window.addEventListener('message', event => {
    if (event.origin.startsWith('https://testpage.com/')) { 
        document.querySelector('.home-title').classList.add('test');
        event.source.postMessage('iframe', event.origin);
    } else {
        
        return; 
    } 
 }); 
}

在我想与 iframe 通信的主页上,我有这段代码,

<script>
  window.onload = function () {
  setTimeout(() => {
     const iframe = document.querySelector('iframe');
     const iframeWindow =  iframe.contentWindow;
     iframeWindow.postMessage("Hello there" , 'https://testIfame.com/');
     alert('here alert pops-u');
  }, 3000)
 

 window.addEventListener('message', function(event) {
     if (event.origin == 'https://testpage.com/'){
       alert('asd');
      } 
    }, false);
  }
</script>

第一个警报有效,它弹出,但没有别的。有人可以帮我解决这个问题。非常感谢。

标签: javascriptiframe

解决方案


推荐阅读