iframe嵌套页面 跨域

iframe嵌套页面 跨域,第1张

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://outofmemory.cn/zaji/586164.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存