Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript iFrame postMessage和addEventListener不工作_Javascript_Html_Iframe_Postmessage - Fatal编程技术网

Javascript iFrame postMessage和addEventListener不工作

Javascript iFrame postMessage和addEventListener不工作,javascript,html,iframe,postmessage,Javascript,Html,Iframe,Postmessage,在阅读了多篇SO文章后,我了解到在iFrame上使用javascript的最佳(或唯一)方法是postMessage和addEventListener。我在网上找到的所有示例代码都显示如下内容: <div id="magazine-container"> <iframe id="iFrame" height="500" width="700" src="https://issuu.com/lideres_mexicanos/docs/351grupoaries-issu

在阅读了多篇SO文章后,我了解到在iFrame上使用javascript的最佳(或唯一)方法是
postMessage
addEventListener
。我在网上找到的所有示例代码都显示如下内容:

<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>
我就是搞不懂这里发生了什么

编辑


我现在明白了,我不是将
addEventListener
附加到iFrame,而是附加到父级。有没有一种方法可以将侦听器添加到实际的iFrame中,而不必访问iFrame中使用的页面的源代码?

当您在框架的内容窗口上调用
postMessage
时,您正在向iFrame发送消息,我相信这是您想要的

但是,您正在将事件侦听器添加到父窗口(也称为
窗口
),而不是iframe的内容窗口。您正在
console.log
ing的消息不是您发送的消息,而是您的页面正在接收的另一条消息。这可能是对您发送的消息的响应,也可能是您安装在浏览器上的插件发送的消息


要实现父级与子级iFrame通信的功能,您必须能够访问iFrame的源代码,以便将事件处理程序附加到那里,或者使用已设置定义API的目标。

感谢您的响应。那么,如果我没有访问源代码的权限,是否无法从iFrame中控制台日志?正确。没有办法做到这一点。这是因为,如果可以,您将能够访问潜在的敏感信息。想象一下,在facebook.com上有一个(隐藏的)iFrame,然后让该facebook.com访问用户的所有私人信息并将其发送回家长网站!这就是为什么有PostMessage机制,所以页面只给出他们明确想要注意的信息,如果您有一个iFrame到一个与父级具有相同主机的页面,那么您实际上拥有完全访问权限,并且不需要依赖postmessagelight,这是有意义的。我一直在想这个问题。我想,这可能是不可能的,也不应该是。哈哈,再次谢谢你!我得到了正确的答案。
{"PrivacyManagerAPI":{"timestamp":1584457115641,"action":"getConsent","self":"quantserve.com","domain":"issuu.com","authority":"truste.com","type":"advertising"}}