今天在坛子看到一帖子,是说在 Chrome下,不能获取iframe的contentWindow。
如果没有跨域的话,这是不可能的,肯定能获取的到才对,所以我写了下面两个测试页面。
page A :
<!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> <mce:style type="text/css"><!-- *{padding:0;margin:0;} --></mce:style><style type="text/css" mce_bogus="1">*{padding:0;margin:0;} </style> </head> <body> <mce:script type="text/javascript"><!-- function show(){ var _iframe = document.getElementById('aa'); _iframe.contentWindow.b(); } function a() { alert('page a'); } // --></mce:script> <iframe id="aa" name="aa" src="4.html" mce_src="4.html" frameborder="0" scrolling="no" width="100%" height="200" ></iframe> <input type="button" value="click" οnclick="show()"/> </body> </html>
page B :
<!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> <mce:style type="text/css"><!-- *{padding:0;margin:0;} --></mce:style><style type="text/css" mce_bogus="1">*{padding:0;margin:0;}</style> </head> <body> <mce:script type="text/javascript"><!-- (function() { parent.window.a(); })(); function b() { alert('page b'); } // --></mce:script> </body> </html>
结果测试了几个常用的浏览器:FF3.6,IE6,Opera10,Safair, Chrome
除了最后一个Chrome,其它的都能正常运行,得到正确的结果。
无语中。。。
于是我打开 Chrome的JS控制器,发现显示了一条JS错误:
Unsafe JavaScript attempt to access frame with URL file:///D:/test/4.html from frame with URL file:///D:/test/3.html . Domains, protocols and ports must match.
意思是说: 在页面3.html和页面4.html之间的javascript是不安全的。域, 协议和端口 必须匹配 才可以。
你说晕不晕...
其它的浏览器都认可直接在浏览器中打开页面3.html时(url=="file:///D:/test/3.html"),和3.html在同一文件夹内的4.html是同域,但 Chrome却不认。
所以我只好开了丢在一边很久的IIS。
在浏览器中输入:http://localhost/test/3.html
测试通过。。。