Google瀏覽器在調試JavaScript指令碼方面很方便,今天在使用Google瀏覽器調試代碼時無意間發現了一個奇特的問題: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:
<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>
</html>
【0分下載代碼檔案】
如果上面代碼在電腦上直接使用Google瀏覽器運行就會出現上面的錯誤“Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols,domains, and ports must match.”,而使用諸如IE瀏覽器直接存取則不會出現這種情況;如果將其使用伺服器(比如Tomcat)發布一下,再次使用Google瀏覽器通過http訪問index.html檔案則不會出現這種情況。
總結:如果在本地用file協議使用Google瀏覽器開啟含有iframe標籤的頁面,則被iframe標籤引用的頁面無法訪問iframe標籤所在頁面的parent對象,除非使用伺服器(比如Tomcat)發布一下。