嵌入 iframe 的頁面,父頁面與子頁面均可以很輕松的在同域或跨子域的情況下進(jìn)行讀寫操作;在完全不同域的情況下,也可以通過更改 hash 的方式進(jìn)行通信。下面我在九個(gè)不同(版本的)瀏覽器中對(duì)此進(jìn)行數(shù)據(jù)傳輸與更改的兼容性測(cè)試。 
同域或跨子域讀寫操作 iframe 里的內(nèi)容
父頁面讀寫操作子頁面:
復(fù)制代碼 代碼如下:
<iframe src="child.html" scrolling="no" frameborder="0"></iframe>
<script>
window.onload = function () {
  /*
   *  下面兩種獲取節(jié)點(diǎn)內(nèi)容的方式都可以。
   *  由于 IE6, IE7 不支持 contentDocument 屬性,所以此處用了通用的
   *  window.frames["iframe Name"] or window.frames[index]
   */
  var d = window.frames["test-iframe"].document;
  d.getElementsByTagName('h1')[0].innerHTML = 'pp';
  alert(d.getElementsByTagName('h1')[0].firstChild.data);
}
</script>
復(fù)制代碼 代碼如下:
<script>
  parent.document.getElementsByTagName('h1')[0].innerHTML = 'pp';
  alert(parent.document.getElementsByTagName('h1')[0].firstChild.data);
</script>
復(fù)制代碼 代碼如下:
<iframe src="http://www.yyy.com/child.html" scrolling="no" frameborder="0"></iframe>
<input type="button" value="send" />
<script>
function sendRequest() {
  document.getElementById('test-iframe').src += '#a';
}
var interval = window.setInterval(function(){
  if(location.hash) {
    alert(location.hash);
    window.clearInterval(interval);
  }
},1000);
</script>
復(fù)制代碼 代碼如下:
<h1>RRRRRR</h1>
<script>
var url = 'http://www.xxx.com/father.html';
    oldHash = self.location.hash,
    newHash,
    interval = window.setInterval(function(){
        newHash = self.location.hash;
        if(oldHash != self.location.hash) {
        document.getElementsByTagName('h1')[0].innerHTML = 'pp';
        //alert(parent.location.href); //去掉這個(gè)注釋,瀏覽器會(huì)提示無權(quán)限
        parent.location.href = url + '#b';
          window.clearInterval(interval);
        }
    },500);
</script>
新聞熱點(diǎn)
疑難解答
圖片精選