父框架如何访问子框架窗口?

时间:2018-05-14 16:45:10

标签: javascript iframe ecmascript-5

在以下代码中:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">    
      </head>
      <body>

        <iframe srcdoc="<script>
                            window.innerStr='xyz';
                        </script>" >
        </iframe>

        <script>

            function test() {
                let iframe = window.frames[0];
                console.log('frames innerStr: ' + iframe.innerStr); // does not work if child frame says innerStr = 'xyz' without window scope
            }
            window.onload = test;  
            test();
        </script>
      </body>
    </html>

对于window.innerStr='xyz';,不在子框架中使用window范围,父框架无法访问子框架属性(innerStr

JS编码是否必须使用窗口范围? window.open('file.html')也有类似的结果。

1 个答案:

答案 0 :(得分:0)

您可以使用消息从父级与iframe通话。

将此代码放在父

// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
    // e.data = "foo"
    doStuff(e.data);
},false);

function doStuff(data){
    console.log(data);
}

将此代码放入iframe

var someVarible = "foo"
parent.postMessage(someVarible, "https://urlofsite.com");

修改 要使用您已有的代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>

<iframe srcdoc="<script>let innerStr='xyz';window.parent.test(innerStr);</script>">
</iframe>

<script>

    function test(foo) {
        var iframe = window.frames[0];
        console.log('frames innerStr: ' + foo)
    }
</script>
</body>
</html>