开幕场景
iframe.html
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- </head>
- <body>
- <a href="javascript:;" onclick="return getIframeDocument()">get iframe input value</a>
- <div class="content" id="content">
- <iframe scrolling="no" frameborder="0" src="inner.html" class="comnet" name="comnet" id="comnet"></iframe>
- </div>
- <script type="text/javascript">
- function getIframeDocument(){
- var iframe = document.getElementById('comnet');
- var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
- if(iframeDocument){
- alert(iframeDocument.getElementById('first').value);
- }else{
- alert("oops!");
- }
- return false;
- }
- window.onload=function(){
- //取iframe
- var iframe = document.getElementById('comnet');
- var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
- if(iframeDocument){
- alert(iframeDocument.getElementById('first').value);
- }else{
- alert("oops!");
- }
- };
- </script>
- </body>
- </html>
inner.html
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>this is iframe document</title>
- </head>
- <body>
- <div id="mainright">ddd</div>
- <div><input type="text" id="first" value="ccc"/></div>
- </body>
- </html>
对白一:chrome我有我的要求
首先把上面的两个html放在非host上,也就是用file:///{path}/iframe.html来访问,当然inner.html也要和它在平级目录,你发现javascript不工作,
Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.
但当他们放到一个站点内它又满血复活.
原因: Chrome会把本地iframe 也当成是跨域
对白二: ie我会72变
在ie6和ie7中对contentDocument不支持,还好ie的版本都支持contentWindow,frames 因此需要下面的代码:
- iframe.contentDocument || iframe.contentWindow.document
但ie10(我的电脑只有ie10)和firefox都可以在用file:///{path}/iframe.html来访问。另外如果把上面的js换成
- var iframe = window.frames["comnet"];
- if(iframe.document){
- alert(iframe.document.getElementById('first').value);
- }else{
- alert("oops!");
- }
发现在ie10中,上面的代码在window.onload事件处理函数中是没有任何效果的。是代码有问题吗?但把它们放到getIframeDocument函数中它又可以工作
对白三: firefox我忠贞如一
上面的ie10问题,chrome问题,在firefox上都没问题