iframe跨域

转载地址: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的使用

官网:http://www.php.cn/phpstudy-377909.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值