跨域postMessage,识别iFrame

Nic*_*o O 14 html javascript xss html5 cross-domain

postMessage用来将iframe中的事件发送到它的父文档.我控制了双方,但内容来自两个不同的领域.

在此输入图像描述

我的简单问题是,我无法识别其内部回调方法中的iFrame.实现如下:

在iFrame中:

parent.postMessage(JSON.stringify({action: "closeView" }),'*');
Run Code Online (Sandbox Code Playgroud)

在父窗口中:

window.addEventListener('message',function(event) {
if(event.origin !== 'https://example.com')
    return;

    // Parse message back to json
    var messageObject = JSON.parse(event.data);
    var source = event.source;
    /* this is returning: Window -URL- */
    console.log( source );
    /* This will throw Permission denied, although this code is inside of "parent" */
    console.log(source.parentNode);
},false);
Run Code Online (Sandbox Code Playgroud)

我想识别iframe的某个父元素,它在(逻辑上)在父文档中.

当我尝试event.source.parentNode在所述对象上使用或使用某些jQuery时,Firefox说,我不能这样做以防止XSS,错误:Error: Permission denied to access property 'parentNode'

我怎样才能获得触发postMessage事件监听器的iFrame的父元素?

dan*_*vis 20

您可以使用窗口名称,因为它们从iframe标记传递到iframe上下文.

父文件:

<iframe name=fr2 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20window.name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>
<iframe name=fr3 src="data:text/html,%3Chtml%3E%0A%20%3Cscript%3E%20parent.postMessage%28%7Bname%3A%20name%7D%2C%20%22*%22%29%3B%3C/script%3E%0A%3C/html%3E"></iframe>

<script>onmessage = function(e){ // use real event handlers in production
       alert("from frame: " + e.data.name);
 };</script>
Run Code Online (Sandbox Code Playgroud)

iframe doc:

<html>
 <script> parent.postMessage({name: name}, "*");</script>
</html>
Run Code Online (Sandbox Code Playgroud)

提醒"fr2",然后"fr3".然后,您可以使用attrib CSS选择器轻松使用名称 attrib在父DOM中查找iframe.

window.name + iframe概念的说明性演示:http://pagedemos.com/namingframes/

这种痛苦的简单方法也不受同一网址iframe引起的问题的影响.


小智 5

根据我的理解,这可能是尝试在这里假设您的主窗口的URL是www.abc.com\home.php

  <body>
         <iframe src="www.abc.com\getOtherDomainContent.php?otherUrl=www.xyz.com"/>
    </body>
Run Code Online (Sandbox Code Playgroud)

此文件中的getOtherDomainContent.php需要编写一个获取交叉URL内容的ajax调用,并将该内容推送到当前iframe窗口(getOtherDomainContent.php)的正文部分.

getOtherDomainContent.php代码:

    <html>
         <head>
//import jqry lib or other you use.
          <script>
              $(document).ready({
               //getcontent of xyz.com
                var otherUrlContent=getAjaxHtml("www.xyz.com");
                 $("body").html(otherUrlContent);
                  // further  code after content pushed.
                  //you can easily access "parent.document" and else using parent which will give you all thing you want to do with your main window
                });
          </script>
         </head>
    </html>
Run Code Online (Sandbox Code Playgroud)