iframe父子頁面相互呼叫的js方法
阿新 • • 發佈:2019-01-05
當父頁面和子頁面都屬於同一個域下,那麼它們之間的js方法是可以相互呼叫的。在呼叫方法前指定function所屬物件即可,父頁面獲取iframe所屬物件方法為:iframe的name.window.方法名(),iframe頁面獲取父頁面所屬物件方法為:parent.方法名()。
但是這裡有一個非常重要的限制,由於瀏覽器基於安全考慮,是不允許js在不同域名間進行通訊,所以父子頁面必須屬於同一個域,即使是相同主域下的不同二級域也是不行的。
對於父子頁面完全屬於兩個不同的域名,那麼它們之間永遠無法直接進行通訊;如果父子頁面是屬於同一個主域下的不同二級域,則可以使用強制設定document.domain的方式來達到讓其互相通訊。document.domain預設值是window.location.host,可以js中設定為window.location.host的上一級域,但是不能為根域,例如:可以在頁面www.duankou.com設定document.domain為duankou.com,但是不能設定為other.duankou.com或com。
document.domain在一定程度上解決了不同二級域名頁面的跨域問題。需要注意的是,如果父頁面包含多個iframe且設定了document.domain,那麼要與其進行通訊的iframe也必須設定document.domain。
另外在chrome 18中,父子頁面屬於相同域名,當設定document.domain後,它們之間變的無法通訊了,其他瀏覽器正常。
父頁面(parent.html):
但是這裡有一個非常重要的限制,由於瀏覽器基於安全考慮,是不允許js在不同域名間進行通訊,所以父子頁面必須屬於同一個域,即使是相同主域下的不同二級域也是不行的。
對於父子頁面完全屬於兩個不同的域名,那麼它們之間永遠無法直接進行通訊;如果父子頁面是屬於同一個主域下的不同二級域,則可以使用強制設定document.domain的方式來達到讓其互相通訊。document.domain預設值是window.location.host,可以js中設定為window.location.host的上一級域,但是不能為根域,例如:可以在頁面www.duankou.com設定document.domain為duankou.com,但是不能設定為other.duankou.com或com。
另外在chrome 18中,父子頁面屬於相同域名,當設定document.domain後,它們之間變的無法通訊了,其他瀏覽器正常。
父頁面(parent.html):
- <!DOCTYPE html >
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
-
<meta http-equiv="Content-Type"
- <title>parent</title>
- </head>
- <body>
- <input type="button" value="call child" onclick="callChild()"/>
- <iframe name="child" src="child.html" ></iframe>
- <script>
- function parentFunction() {
-
alert('function in parent'
- }
- function callChild() {
- //child 為iframe的name屬性值,不能為id,因為在FireFox下id不能獲取iframe物件
- child.window.childFunction();
- }
- </script>
- </body>
- </html>
- <!DOCTYPE html >
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>child</title>
- </head>
- <body>
- <input type="button" value="call parent" onclick="callParent()"/>
- <script>
- function childFunction() {
- alert('function in child');
- }
- function callParent() {
- parent.parentFunction();
- }
- </script>
- </body>
- </html>