天天看點

谷歌浏覽器的一個新特點——關于擷取iframe的parent對象

        谷歌浏覽器在調試JavaScript腳本方面很友善,今天在使用谷歌浏覽器調試代碼時無意間發現了一個奇特的問題:Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.,這主要是沒有擷取iframe所在頁面的parent的造成的,代碼如下:

        index.html:

       <html>

                 <head>

                            <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

                            <script type="text/javascript">

                                         function test() {

                                                alert(‘您成功調用了iframe标簽所在頁面的函數!‘);

                                         }

                           </script>

                 </head>

                 <body>

                          <iframe frameborder="1" src=‘child.html‘ style="width:50%; height:50%;" ></iframe>

                          <div style="font-size: 36px; margin-left: 40%; color: red;">iframe标簽所在頁面</div>

                 </body>

       </html>

       child.html:

                   <head>

                           <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

                   </head>

                  <body>

                          <input type="button" onclick="javascript:window.parent.test();" value="調用iframe标簽所在頁面的函數"/>

                          <div style="font-size: 21px; margin-left: 40%; color: red;">iframe标簽所引用的頁面</div>

                  </body>

       【】

       如果上面代碼在電腦上直接使用谷歌浏覽器運作就會出現上面的錯誤“Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols,domains, and ports must match.”,而使用諸如IE浏覽器直接通路則不會出現這種情況;如果将其使用伺服器(比如Tomcat)釋出一下,再次使用谷歌浏覽器通過http通路index.html檔案則不會出現這種情況。

       總結:如果在本地用file協定使用谷歌浏覽器打開含有iframe标簽的頁面,則被iframe标簽引用的頁面無法通路iframe标簽所在頁面的parent對象,除非使用伺服器(比如Tomcat)釋出一下。