chrome中iframe交互问题

环境:ie11,chrome43

parent.html

[html]  view plain  copy
  1. <html>  
  2. <head>  
  3. <script type="text/javascript">  
  4. function modiframe()  
  5. {  
  6.     var ifr_doc = document.getElementById("iframe1").contentDocument;  
  7.     ifr_doc.getElementById("label1").innerHTML = "改变了";  
  8. }  
  9. </script>  
  10. </head>  
  11. <body>  
  12. <button onclick="modiframe()">改值</button>  
  13. <iframe id="iframe1" src="a.html"></iframe>  
  14. </body>  
  15. </html>  

a.html

[html]  view plain  copy
  1. <html>  
  2. <body>  
  3. <label id="label1">child</label>  
  4. </body>  
  5. </html>  

本地测试,在parent.html中点击按钮,在ie11和firefox39都有效果,

chrome报错:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

错误行代码:

var ifr_doc = document.getElementById("iframe1").contentDocument;

原因:跨域,file:///类型的也算跨域,chrome对于file协议有安全限制,无法用js访问本地资源,对于http则是好的,所以上面页面要是在iis/apache网站中打开应该是没问题的

参考:http://bbs.csdn.net/topics/390894709

http://my.oschina.net/freax/blog/305164?p=1

http://bbs.csdn.net/topics/390910056

解决:

因为我的子页面较小,故直接动态创建iframe元素,不使用a.html

parent.html

[html]  view plain  copy
  1. <html>  
  2. <head>  
  3. <script type="text/javascript">  
  4.     var ifr_doc;  
  5.     function OnLoad() {  
  6.         var iframe = document.createElement('iframe');  
  7.         var ifr = document.body.appendChild(iframe);  
  8.         ifr_doc = ifr.contentWindow.document;  
  9.   
  10.         ifr.frameborder = '1px';  
  11.         ifr.height = '100px';  
  12.         ifr.width = '100px';  
  13.         ifr.style.display = 'inline';  
  14.   
  15.         var loadjs = '<html><body><label id=\"label1\">child</label></body></html>';  
  16.   
  17.         ifr_doc.open();  
  18.         ifr_doc.write(loadjs);  
  19.         ifr_doc.close();  
  20.     }  
  21.     function modiframe() {  
  22.         ifr_doc.getElementById("label1").innerHTML = "改变了";  
  23.     }  
  24. </script>  
  25. </head>  
  26. <body onload="OnLoad()">  
  27. <button onclick="modiframe()">改值</button>  
  28. </body>  
  29. </html>  

参考:http://www.xuebuyuan.com/286558.html

除此之外,还有两种技术解决chrome的iframe加载问题,但我没试

1.html5的postMessage

2.在网站中部署,而非本地打开

发布了11 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/LYW_lyw/article/details/80308260