• 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>
  • 相关阅读:
    第一阶段各队建议
    解决死锁四大方式
    进程和线程区别
    windows 地址空间分配
    Linux下用户组、文件权限详解
    2016总结
    class内部处理
    c++ devived object model
    static
    reinterpret
  • 原文地址:https://www.cnblogs.com/cxx8181602/p/11174662.html
Copyright © 2020-2023  润新知