iFrame postMessage 和 addEventListener 不工作

iFrame postMessage and addEventListener not working

阅读多篇 SO 帖子后,我了解到在 iFrame 上使用 javascript 的最佳(或唯一)方法是 postMessageaddEventListener。我在网上找到的所有示例代码都是这样的:

<div id="magazine-container">
    <iframe id="iFrame" height="500" width="700" src="https://issuu.com/lideres_mexicanos/docs/351grupoaries-issuu/76"></iframe>
</div>

<script>
    $(document).ready(function () {
        let testString = 'MESSAGE FROM LOCALHOST';
        let frame = document.getElementById('iFrame');
        frame.contentWindow.postMessage(testString, '*');

        window.addEventListener('message', event => {
            console.log(event.data);
        });
    });
</script>

查看控制台,event.data 不包含变量 testString。 相反,它包含以下内容:

{"PrivacyManagerAPI":{"timestamp":1584457115641,"action":"getConsent","self":"quantserve.com","domain":"issuu.com","authority":"truste.com","type":"advertising"}}

我就是想不通这是怎么回事。

编辑

我现在明白我没有将 addEventListener 附加到 iFrame,而是附加到父级。有没有办法将侦听器添加到实际的 iFrame 而无需访问 iFrame 中使用的页面的源代码?

当您在 frame 的 contentWindow 上调用 postMessage 时,您正在向 iFrame 发送消息,正如我相信的那样。

但是,您正在向父级 window(又名 window)添加事件侦听器,不是 iframe 的内容 window。您console.log发送的消息不是您发送的消息,而是您的页面收到 的另一条消息。这可能是对您发送的消息的回复,或者是您在浏览器上安装的插件发送的消息。

要实现父 iFrame 与子 iFrame 通信的功能,您必须能够访问 iframe 的源代码,以便您可以在其中附加事件处理程序,或者使用具有已定义 API 已经设置好。