iframe嵌套頁面 跨域


父級調用iframe方法:

document.getElementById("iframe").contentWindow.func(data1,data2...)

子級 iframe中調用 父級html中方法:

parent.func(data1,data2...)

使用的前提條件是要在同域名下,想要如果域名不同,甚至端口不同,都會存在 跨域 的問題。

 

簡單示例demo:   

a.html 頁面

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>A</title> 
</head> 
<body> 
    父級:A頁面<br/>
    <textarea id="a_text">來自B頁面密碼...</textarea><br/> 
    <button id="a_button">A頁面獲取B頁面數據</button><br/><br/>
    <iframe src="b.html" width="500px" height="200px" id="iframe"></iframe> 
<!--     <iframe src="b.html" width="500px" height="200px" id="iframe" frameborder="0" scrolling="no" style="position:absolute;right:0;left:0"></iframe> -->
    <script> 
    document.getElementById("a_button").onclick = function(){ 
    alert(document.getElementById("iframe").contentWindow.document.getElementById("b_text").value); 
  }
    </script> 
</body> 
</html>

b.html 頁面

<html>
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>B</title>
</head>
<body> 
    子級:B頁面<br/>
    <textarea id="b_text">來自A頁面密碼...</textarea><br/>
    <button id="b_button">B頁面獲取A頁面數據</button><br/> 
    <script> 
    document.getElementById("b_button").onclick = function(){ 
        alert(parent.document.getElementById("a_text").value); 
    } 
    </script>
</body>
</html>

 

使用window.postMessage方法解決跨域:

簡單示例demo:

a.html 頁面

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>A</title> 
</head> 
<body> 
    父級:A頁面<br/><br/>
    <iframe src="b.html" width="500px" height="200px" id="iframe"></iframe> 
    <script> 
        window.addEventListener('message', function(e) {
            alert(JSON.stringify(e.data));
            console.log('獲取子級B頁面返回值:');
            console.log(e.data);
        })

    </script> 
</body> 
</html>

b.html 頁面

<html>
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>B</title>
</head>
<body> 
    子級:B頁面<br/>
    <button id="b_button">B頁面發送A頁面數據</button><br/> 
    <script> 
    document.getElementById("b_button").onclick = function(){ 
        var param = {'name':'admin'};
        window.parent.postMessage(param,'*');
    } 
    </script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM