欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

關(guān)于Javascript與iframe的那些事兒

 更新時(shí)間:2013年07月04日 12:04:58   作者:  
iframe 很多網(wǎng)站都在用,雖然方便開發(fā)與維護(hù)(可能同時(shí)有幾個(gè)頁面調(diào)用同一個(gè) iframe ),不過卻存在安全問題
嵌入 iframe 的頁面,父頁面與子頁面均可以很輕松的在同域或跨子域的情況下進(jìn)行讀寫操作;在完全不同域的情況下,也可以通過更改 hash 的方式進(jìn)行通信。下面我在九個(gè)不同(版本的)瀏覽器中對此進(jìn)行數(shù)據(jù)傳輸與更改的兼容性測試。
同域或跨子域讀寫操作 iframe 里的內(nèi)容
父頁面讀寫操作子頁面:
復(fù)制代碼 代碼如下:

<iframe id="test-iframe" name="test-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>

注:在請務(wù)必通過 window.onload 方法訪問 iframe 中的節(jié)點(diǎn),否則瀏覽器會提示錯(cuò)誤-拒絕訪問。在 IE8, Firefox3.6, Opera11 下在DOMReady 時(shí)也可以訪問 iframe 中的節(jié)點(diǎn)。
子頁面讀寫操作父頁面:
復(fù)制代碼 代碼如下:

<script>
  parent.document.getElementsByTagName('h1')[0].innerHTML = 'pp';
  alert(parent.document.getElementsByTagName('h1')[0].firstChild.data);
</script>

小結(jié):
•1 測試通過 IE6, IE7, IE8, Firefox2.0, Firefox3.0, Firefox3.6, Chrome8, Opera11, Safari5.
•2 查閱資料得出 document.getElementById(‘id name').contentDocument 全等于 window.frames["iframe Name"].document.
•3 跨子域時(shí),需要在父頁面和子頁面 JS 中分別加上 document.domain = 'xxx.com';
跨域操作 iframe 里內(nèi)容
當(dāng)兩個(gè)網(wǎng)頁所在域不同時(shí),要實(shí)現(xiàn)數(shù)據(jù)的互相調(diào)用,只能通過 JS 改變 location 對象的 hash 屬性的值來做到互相通信。
父頁面:
復(fù)制代碼 代碼如下:

<iframe id="test-iframe" src="http://www.yyy.com/child.html" scrolling="no" frameborder="0"></iframe>
<input type="button" value="send" onclick="sendRequest()" />
<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è)注釋,瀏覽器會提示無權(quán)限
        parent.location.href = url + '#b';
          window.clearInterval(interval);
        }
    },500);
</script>

小結(jié):
•1 經(jīng)測試 IE6, IE7, IE8, Firefox2.0, Firefox3.0, Firefox3.6, Chrome8, Opera11, Safari5, 除 IE6, IE7 外只要改變hash 就會記錄在瀏覽器 history 中。
•2 我有試圖在子頁面用 parent.location.replace 的方法來避免父頁面向服務(wù)器發(fā)送請求而進(jìn)行跳轉(zhuǎn),這樣理論上瀏覽器就不會記錄歷史,但未能奏效。
•2 子頁面無權(quán)讀取父頁面的 url, 但可以對父頁面的 url 進(jìn)行寫操作,所以跨域操作時(shí),要提前得知父頁面的url
由于前端解決跨域問題的局限性比較大,所以最好用服務(wù)器端解決方案

相關(guān)文章

最新評論