html框架跨域名,iframe操作(跨域解决等)_html/css_WEB-ITnose

5268f80b9b1e01f982625ef6fac83ca1.png

note:当页面内嵌入一个iframe实际上是在dom上新建了一个新的完整的window对象

iframe中取得主窗体

window.top (顶级窗口的window对象)

window.parent (当前iframe的父窗体window)

多层嵌套的iframe window.parent.parent....来取

取得需要的window后可进行操作父文档的内容

如: window.top.document.getElementById(''xxx");

主窗体中取得iframe所属的window对象

window.frames['iframe的名字'] (通过iframe上的name属性)

document.getElementById("HtmlEdit").contentWindow; (通过原生的方式,所有主要浏览器都支持 contentWindow 属性)

示例:

参考: http://blog.csdn.net/dongzhiquan/article/details/5851201

如(主窗口中操作iframe刷新):

document.getElementById('FrameID').contentWindow.location.reload(true);

也可以直接jquery操作attr刷新: $('#frameID').attr('src','http://xxx');

浏览器同源策略:1.不能通过ajax的方法去请求不同源中的文档 2.浏览器中不同域的框架之间是不能进行js的交互操作的

如果iframe涉及到跨域,这时进行iframe window对象的操作会访问受限

chrome提示:

Uncaught SecurityError: Blocked a frame with origin "http://123.57.6.131" from accessing a frame with origin "http://localhost:9000". Protocols, domains, and ports must match.

firefox提示:

Permission denied to access property "xxx"

这里有两种情况,

1.子级域名之间跨域

2.完全不同域名跨域

1.子级域名之间跨域操作,指定相同的document.domain即可

如:

http://www.example.com/a.html 和 http://example.com/b.html

这两个页面的document.domain都设成相同的域名就可以了 example.com

只能把document.domain设置成自身或更高一级的父域,且主域必须相同,然后即可无阻访问,进行相应操作

2.完全不同域的情况,传值 (通过iframe所属的window对象的location.hash传值)

2.1 主窗体传值给iframe

由于操作location.hash不会造成整个iframe的重载刷新,所以可以这样操作,然后在iframe中监听onhashchange事件

如:

//主窗体中传递json数据到iframe:var url;var data = {name:'xx',age:26};var tmp = encodeURI( JSON.stringify(center) );$('#iframe_id').attr('src',url+'#'+tmp);//iframe中接收 window.onhashchange = function () { var hash_str = decodeURI( window.location.hash.replace('#','').toString() ); var data = JSON.parse( hash_str ); }// 这样一旦当url hash值改变,iframe就可以进行相应调整// 如果要兼容ie8之类不支持onhashchange事件的浏览器// 可以用setInterval()判断是否发生改变,然后调用相应函数

参考: http://stackoverflow.com/questions/3090478/jquery-hashchange-event

2.2 iframe中传递给主窗体

需要在主窗体a同域名下新建一个页面c

然后在iframe b中嵌入iframe src值为页面c,

iframe b中便可用同样的方式操作c的url hash值,

a,c同域名下即可透明访问操作, a访问c的window对象不存在跨域同源限制的问题.

1428d0e076c3959ab11d28a39bc84fab.png

5268f80b9b1e01f982625ef6fac83ca1.png

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值