IE下因设置document.domain而无法和Iframe通信的解决方法
最近在开发SDK的过程中发现IE下有个很怪异的问题:在同一域下,因在父页面上设置了document.domain,而导致无法正常和Iframe(也是同域下)进行通信,IE下抛出的错误是:SCRIPT5: 拒绝访问,导致无法操作iframe中的内容。
经过查阅了很多资料后发现IE下,在父页面或在iframe页面中,只要设置了document.domain,无论是和当前域名相同还是根域名,均视为跨域,所以才会出现拒绝访问的错误,即使你这样写document.domain=document.domain;虽然好像没人这么干。
那么如何才能解决这个问题,让父页面和iframe页面正常通信呢,根据同源策略,让双方均设置同样的domain就可以达到目的。
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //访问地址:http://www.a.com/a.html <html> <head> <title>Iframe</title> </head> <body> <script type= "text/javascript" > document.domain = 'a.com' ; var iframe = document.createElement( "iframe" ); document.body.appendChild(iframe); if (/msie/i.test(navigator.userAgent)){ try { iframe.contentWindow.document; } catch (e) { iframe.onload = function () { console.log(iframe.contentWindow.document.location); iframe.onload = null ; } iframe.src = "javascript:void((function(){document.open();document.domain='" + document.domain + "';document.close()})())" ; } } </script> </body> </html>
|