簡體   English   中英

父框架如何訪問子框架窗口?

[英]How parent frame access child frame window?

在下面的代碼中:

    <!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')具有相似的結果。

您可以使用消息從父級與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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM