国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

關于Javascript與iframe的那些事兒

2019-11-20 22:34:24
字體:
來源:轉載
供稿:網友
嵌入 iframe 的頁面,父頁面與子頁面均可以很輕松的在同域或跨子域的情況下進行讀寫操作;在完全不同域的情況下,也可以通過更改 hash 的方式進行通信。下面我在九個不同(版本的)瀏覽器中對此進行數據傳輸與更改的兼容性測試。
同域或跨子域讀寫操作 iframe 里的內容
父頁面讀寫操作子頁面:
復制代碼 代碼如下:

<iframe id="test-iframe" name="test-iframe" src="child.html" scrolling="no" frameborder="0"></iframe>
<script>
window.onload = function () {
  /*
   *  下面兩種獲取節點內容的方式都可以。
   *  由于 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>

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

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

小結:
•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 跨子域時,需要在父頁面和子頁面 JS 中分別加上 document.domain = 'xxx.com';
跨域操作 iframe 里內容
當兩個網頁所在域不同時,要實現數據的互相調用,只能通過 JS 改變 location 對象的 hash 屬性的值來做到互相通信。
父頁面:
復制代碼 代碼如下:

<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>

子頁面:
復制代碼 代碼如下:

<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); //去掉這個注釋,瀏覽器會提示無權限
        parent.location.href = url + '#b';
          window.clearInterval(interval);
        }
    },500);
</script>

小結:
•1 經測試 IE6, IE7, IE8, Firefox2.0, Firefox3.0, Firefox3.6, Chrome8, Opera11, Safari5, 除 IE6, IE7 外只要改變hash 就會記錄在瀏覽器 history 中。
•2 我有試圖在子頁面用 parent.location.replace 的方法來避免父頁面向服務器發送請求而進行跳轉,這樣理論上瀏覽器就不會記錄歷史,但未能奏效。
•2 子頁面無權讀取父頁面的 url, 但可以對父頁面的 url 進行寫操作,所以跨域操作時,要提前得知父頁面的url
由于前端解決跨域問題的局限性比較大,所以最好用服務器端解決方案
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南郑县| 平乡县| 霍城县| 遂宁市| 桂东县| 阜南县| 三原县| 那曲县| 新田县| 岳普湖县| 周口市| 永和县| 抚远县| 精河县| 手机| 崇文区| 望都县| 通州区| 柘城县| 友谊县| 安顺市| 湖州市| 大洼县| 新竹市| 昭通市| 延吉市| 巴彦淖尔市| 边坝县| 家居| 蒲江县| SHOW| 蛟河市| 辉县市| 武义县| 侯马市| 通山县| 长武县| 牟定县| 社会| 无为县| 宁化县|