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>

 

转载于:https://www.cnblogs.com/cxx8181602/p/11174662.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值