转载地址:https://blog.csdn.net/tcf_jingfeng/article/details/80068113
父页面1.html(域名为:http://127.0.0.1:8020/11/11/1.html)中有一个iframe标签引入(src)一个2.html(域名为:http://1.com/2.html)的页面,这就会出现跨域的情况。
思路:在2.html通域名下建立一个3.html(域名:http://1.com/3.html),同时在1.html这个父页面底部新建一个iframe引入3.html,在3.html中对2.html进行操作(这是3.html相对于2.html就是相同域名了);
1.代码
(1)1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<iframe id="myframe" name="myframe" src="http://1.com/2.html" frameborder="1" style="" width="720" height="400"></iframe>
<script type="text/javascript">
window.onload = function(ev) {
function exec_iframe() {
if(typeof(exec_obj) == 'undefined') {
exec_obj = document.createElement('iframe');
exec_obj.name = 'tmp_frame';
exec_obj.src = 'http://1.com/3.html';
exec_obj.style.display = 'none';
document.body.appendChild(exec_obj); //动态创建一个iframe
} else {
exec_obj.src = 'http://1.com/3.html?a=' + Math.random();
}
}
exec_iframe()
}
</script>
</body>
</html>
(2)2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
test9001
<div id="notebook">
<p>这个页面放到iframe里面,目标获取这里的内容就算成功</p>
</div>
</body>
</html>
(3)3.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
<script src="http://lib.baomitu.com/jquery/3.3.1/jquery.js"></script>
<script>
//jquery操作方式,变个颜色
// $('#notebook', window.parent.myframe.document).css("backgroundColor","red")
//js的操作方式,变个颜色
parent.window.frames["myframe"].document.getElementById("notebook").style.backgroundColor = "green";
var temp = parent.window.frames["myframe"].document.getElementById("notebook").innerHTML; //取值
console.log(temp)
</script>
2.效果
3.推荐
博客:https://blog.csdn.net/tcf_jingfeng/article/details/80068113
专栏:https://segmentfault.com/a/1190000011145364?utm_source=tag-newest
博客:https://www.cnblogs.com/2050/p/3191744.html
转载地址:https://blog.csdn.net/tcf_jingfeng/article/details/80068113
4.如果想本地尝试,可以用phpstudy来模拟不用域名的场景,phpstudy的使用