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

iframe子頁面與父頁面在同域或不同域下的js通信

 更新時間:2014年05月07日 09:04:04   作者:  
根據(jù)iframe中src屬性是同域鏈接還是跨域鏈接,通信方式也不同,下面有個不錯的示例,需要的朋友可以參考下
iframe子頁面與父頁面通信根據(jù)iframe中src屬性是同域鏈接還是跨域鏈接,通信方式也不同。

一、同域下父子頁面的通信

父頁面parent.html
復(fù)制代碼 代碼如下:

<html>
<head>
<script type="text/javascript">
function say(){
alert("parent.html");
}
function callChild(){
myFrame.window.say();
myFrame.window.document.getElementById("button").value="調(diào)用結(jié)束";
}
</script>
</head>
<body>
<input id="button" type="button" value="調(diào)用child.html中的函數(shù)say()" onclick="callChild()"/>
<iframe name="myFrame" src="child.html"></iframe>
</body>
</html>

子頁面child.html
復(fù)制代碼 代碼如下:

<html>
<head>
<script type="text/javascript">
function say(){
alert("child.html");
}
function callParent(){
parent.say();
parent.window.document.getElementById("button").value="調(diào)用結(jié)束";
}
</script>
</head>
<body>
<input id="button" type="button" value="調(diào)用parent.html中的say()函數(shù)" onclick="callParent()"/>
</body>
</html>

方法調(diào)用

父頁面調(diào)用子頁面方法:FrameName.window.childMethod();

子頁面調(diào)用父頁面方法:parent.window.parentMethod();
DOM元素訪問

獲取到頁面的window.document對象后,即可訪問DOM元素
注意事項(xiàng)

要確保在iframe加載完成后再進(jìn)行操作,如果iframe還未加載完成就開始調(diào)用里面的方法或變量,會產(chǎn)生錯誤。判斷iframe是否加載完成有兩種方法:

1. iframe上用onload事件

2. 用document.readyState=="complete"來判斷

二、跨域父子頁面通信方法

如果iframe所鏈接的是外部頁面,因?yàn)榘踩珯C(jī)制就不能使用同域名下的通信方式了。
父頁面向子頁面?zhèn)鬟f數(shù)據(jù)

實(shí)現(xiàn)的技巧是利用location對象的hash值,通過它傳遞通信數(shù)據(jù)。在父頁面設(shè)置iframe的src后面多加個data字符串,然后在子頁面中通過某種方式能即時的獲取到這兒的data就可以了,例如:

1. 在子頁面中通過setInterval方法設(shè)置定時器,監(jiān)聽location.href的變化即可獲得上面的data信息

2. 然后子頁面根據(jù)這個data信息進(jìn)行相應(yīng)的邏輯處理

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

實(shí)現(xiàn)技巧就是利用一個代理iframe,它嵌入到子頁面中,并且和父頁面必須保持是同域,然后通過它充分利用上面第一種通信方式的實(shí)現(xiàn)原理就把子頁面的數(shù)據(jù)傳遞給代理iframe,然后由于代理的iframe和主頁面是同域的,所以主頁面就可以利用同域的方式獲取到這些數(shù)據(jù)。使用 window.top或者window.parent.parent獲取瀏覽器最頂層window對象的引用。

相關(guān)文章

最新評論