1. 程式人生 > >iframe父子頁面相互呼叫的js方法

iframe父子頁面相互呼叫的js方法

當父頁面和子頁面都屬於同一個域下,那麼它們之間的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):
  1. <!DOCTYPE html >  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type"
     content="text/html; charset=utf-8" />  
  5. <title>parent</title>  
  6. </head>  
  7. <body>  
  8. <input type="button" value="call child" onclick="callChild()"/>  
  9. <iframe name="child" src="child.html" ></iframe>  
  10. <script>  
  11. function parentFunction() {  
  12.     alert('function in parent'
    );  
  13. }  
  14. function callChild() {  
  15.     //child 為iframe的name屬性值,不能為id,因為在FireFox下id不能獲取iframe物件
  16.     child.window.childFunction();  
  17. }  
  18. </script>  
  19. </body>  
  20. </html>  
子頁面(iframe頁面,child.html):
  1. <!DOCTYPE html >  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>child</title>  
  6. </head>  
  7. <body>  
  8. <input type="button" value="call parent" onclick="callParent()"/>  
  9. <script>  
  10. function childFunction() {  
  11.     alert('function in child');  
  12. }  
  13. function callParent() {  
  14.     parent.parentFunction();  
  15. }  
  16. </script>  
  17. </body>  
  18. </html>