iframe操作(跨域解决等)_html/css_WEB-ITnose

WBOY
Freigeben: 2016-06-24 11:22:04
Original
1558 Leute haben es durchsucht

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()判断是否发生改变,然后调用相应函数
Nach dem Login kopieren

参考: 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对象不存在跨域同源限制的问题.

 

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!