iframe跨域访问

js跨域是个讨论很多的话题。iframe跨域访问也被研究的很透了。

一般分两种情况:

一、 是同主域下面,不同子域之间的跨域;

  同主域,不同子域跨域,设置相同的document.domian就可以解决;

     父页访问子页,可以document.getElementById("myframe").contentWindow.document来访问iframe页面的内容;如果支持contentDocument也可以直接document.getElementById("myframe").contentDocument访问子页面内容;

  子页访问父页,可以parent.js全局属性

二、 是不同主域跨域;

  前提,www.a.com下a.html,a.html内iframe调用了www.b.com下的b.html,b.html下iframe调用了www.a.com下的c.html

  b.html是不无法直接访问a.html的对象,因为涉及到跨域,但可以访问parent,同样c.html的parent可以访问b.html。c.html和a.html同域,是可以访问a下的对象的。parent.parent.js对象!

  看下面实例:

  a.html

复制代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<iframe src="http://www.b.com/b.html" ></iframe>
<ul id="getText"></ul>
<script>
    function dosome(text){
        document.getElementById("getText").innerHTML= decodeURI(text);    
    }
</script>
</body>
</html>
复制代码

b.html

复制代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<iframe id="myfarme" src="###"></iframe>
<ul id="ct">
<li>这里是内容1</li>
<li>这里是内容2</li>
<li>这里是内容3</li>
<li>这里是内容4</li>
<li>这里是内容5</li>
<li>这里是内容6</li>
</ul>
<script>
    window.onload = function(){
        var text = document.getElementById('ct').innerHTML;
        document.getElementById('myfarme').src="http://www.a.com/c.html?content="+encodeURI(text);
    }
</script>
</body>
</html>
复制代码

c.html

复制代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
window.onload = function(){
    var text = window.location.href.split('=')[1]
    console.log(parent.parent)
    parent.parent.dosome(text);
}
</script>
</head>

<body>
ddddddddddd
</body>
</html>
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现iframe跨域访问页面,需要满足以下条件: 1. 父页面和子页面都是自己可以控制的。 2. 被嵌入的页面不属于同一个域名、协议或端口号的源。 实现iframe跨域访问页面可以采用以下方法: 1. 使用postMessage:通过在父页面和子页面之间进行消息传递,可以安全地实现跨域通信。父页面可以使用`window.postMessage()`方法向子页面发送消息,子页面可以通过监听`message`事件接收并处理这些消息。这种方式允许双向通信,并且在不同的窗口间传递数据时更加安全可靠。 2. 设置document.domain:如果父页面和子页面具有相同的顶级域名,但不同的子域名,可以通过设置相同的document.domain来实现跨域访问。例如,如果父页面的域名是`example.com`,子页面的域名是`sub.example.com`,可以在父页面和子页面中都设置`document.domain = "example.com"`。这样,它们就可以进行跨域通信。 3. 使用CORS(跨域资源共享):在服务器端配置响应文件的HTTP头,允许来自其他域的页面访问。服务器需要设置特定的响应头,包括`Access-Control-Allow-Origin`来指定允许访问的域名。 总结起来,要实现iframe跨域访问页面,可以使用postMessage、设置document.domain或使用CORS来进行跨域通信。这些方法都可以确保安全地进行跨域访问,并实现在父页面和子页面之间的数据传递和通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值