一旦接收到iFrame的响应,就捕获该响应

Catching the response of the iFrame once receiving the response

本文关键字:响应 iFrame      更新时间:2023-09-26

我正在向iFrame发布消息。iFrame以布尔值形式返回响应。当响应从iFrame到达父窗口时,我需要捕捉响应。我的代码不起作用。知道这个吗?

iFrame

<iframe id="opIFrame"  src="https://localhost:9443/oauth2/session" >
</iframe>

我定期向iFrame 发送消息

var iframe = document.getElementById("opIFrame");
    setInterval(function(){
        message ='test' ;
        console.log('Request From RP: ' + message);
        iframe.contentWindow.postMessage(message,"https://localhost:9443/oauth2/session"); 
    },6000);

我需要做的是定期接收iFrame的响应。到目前为止,代码正在工作。我为iframe添加了一个事件监听器,如下所示。

 iframe.addEventListener("message",test,false);
    function test(event){
        alert("test");
    }

但它不是周期性地发射

实际上非常简单:您在iframe上添加了侦听器(作为父窗口DOM的元素),而不是在iframe的窗口上。只要解决这个问题,它就会起作用:

iframe.contentWindow.addEventListener("message",test,false);