好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

如(主窗口中操作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对象不存在跨域同源限制的问题.

查看更多关于iframe操作(跨域解决等)_html/css_WEB-ITnose的详细内容...

  阅读:154次