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

JS如何對Iframe內外頁面進行操作總結

 更新時間:2021年10月12日 15:56:41   作者:道系小布丁  
iframe標簽是一個內聯(lián)框架,即用來在當前HTML頁面中嵌入另一個文檔的,且所有主流瀏覽器都支持iframe標簽,這篇文章主要給大家介紹了關于JS如何對Iframe內外頁面進行操作的相關資料,需要的朋友可以參考下

在iframe外獲取iframe里的內容

方式一

通過contentWindow和contentDocument這兩個API:

var iframe = document.getElementById("iframe1");
var iwindow = iframe.contentWindow;
var idoc = iwindow.document;
var idocument = iframe.contentDocument;
console.log("window",iwindow);//獲取iframe的window對象
console.log("document",idoc);  //獲取iframe的document
console.log("html",idoc.documentElement);//獲取iframe的html

其中iframe.contentWindow可以獲取iframe的window對象,iframe.contentDocument可以獲取iframe的document對象。

方式二

結合Name屬性,通過window提供的frames獲取:

<iframe src ="/index.html" id="ifr1" name="ifr2" scrolling="yes">
  <p>Your browser does not support iframes.</p>
</iframe>
<script type="text/javascript">
    console.log(window.frames['ifr2'].window);
    console.dir(document.getElementById("iframe").contentWindow);
</script>

在iframe內獲取iframe外的內容

window.parent 獲取上一級的window對象,如果還是iframe則是該iframe的window對象
window.top 獲取最頂級容器的window對象,即,就是你打開頁面的文檔

在iframe中調用父頁面中定義的方法和變量

window.parent.window.parentMethod();
window.parent.window.parentValue;

在父頁面操作iframe子頁面的方法和變量

window.frames["iframe_Name"].window.childMethod();
window.frames["iframe_Name"].window.childValue;

總結

在使用Iframe時還需要注意以下兩點:

  1. 要確保在iframe加載完成后再進行操作,如果iframe還未加載完成就開始調用里面的方法或變量,會產(chǎn)生錯誤;
  2. 如果iframe所鏈接的是外部頁面,因為安全機制不能使用同域名下的通信方式;

判斷iframe加載完成

iframe.onload = function() {
    // TODO
}

不同域通信

父頁面向子頁面?zhèn)鬟f數(shù)據(jù)

利用location對象的hash值,通過它傳遞通信數(shù)據(jù)。在父頁面設置iframe的src后面多加個data字符串,然后在子頁面中通過某種方式能即時的獲取到這兒的data。

子頁面向父頁面?zhèn)鬟f數(shù)據(jù)

利用一個代理iframe,它嵌入到子頁面中,并且和父頁面必須保持是同域,然后通過它充分利用上面同域通信方式的實現(xiàn)原理,把子頁面的數(shù)據(jù)傳遞給代理iframe,然后由于代理的iframe和主頁面是同域的,所以主頁面就可以利用同域的方式獲取到這些數(shù)據(jù)。

到此這篇關于JS如何對Iframe內外頁面進行操作的文章就介紹到這了,更多相關JS對Iframe頁面操作內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論