2017-03-04 186 views
1

我使用Javascript單擊按鈕並在彈出窗口中顯示它,動態創建iframe。
在Iframe中,我正在加載另一個網站(不同的域),它由從第一步到最後一步的用戶的表單序列組成。
當用戶處於最後一步時,他將在Iframe內獲得一個關閉按鈕。
我想關閉(隱藏)單擊關閉按鈕時包含Iframe的彈出窗口。
可能嗎?請幫忙。關閉包含Iframe的Popup,單擊iframe上的按鈕

回答

2

後瀏覽網頁尋找解決辦法,我碰到這個soultion來小時。
這裏的問題是,同源策略會阻止腳本訪問其他來源網站內容。
其實原點由以下幾部分組成。

origin:<protocol(http/https)>://<hostname>:<port number>/path/to/page.html 

起源被認爲是不同的,如果協議主機名端口號沒有same.In這種情況下,你不能從其他網站訪問一個網站的內容,由於相同 - 原始安全政策。

爲了克服它,你必須使用通過window.postMessage()親子溝通
供參考:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Window.postMessage()方法安全地啓用了跨源通信。
假設你的父母的網站是example-parent.com並在您的iFrame加載網站example-iframe.com,讓兩者都使用HTTP協議。 以下是我如何解決問題。
在父網站中添加要接收消息的事件偵聽器,如下所示。

window.addEventListener('message',receiveMessage,false); 

function receiveMessage(event){ 
    var origin = event.origin || event.originalEvent.origin; 
    if(origin.indexOf('http://example-iframe.com')>=0) // check if message received from intended sender 
    { 
     if(event.data=="intended message format") // check if data received is in correct format 
     { 
      // call functionality that closes popup containing iframe 
     }else{ // data received is malacious 
      return; 
     } 

    }else{ // message is not received from intended sender 
     return; 
    } 
} 

從Iframe發送消息到父網站如下。
帖子消息語法:otherWindow.postMessage(message, targetOrigin, [transfer]);

function sendMessage(){ 
    parent.postMessage('intended message format','http://example-parent.com'); 
} 

使用的postMessage()正確,否則可能會導致跨站點腳本攻擊。

+1

另外,如果你的事件監聽器正在引起一些網絡調用,建議檢查收到的消息的速率,這是爲了防止DOS攻擊。 – nak

0

因爲我正確理解你想調用一個關閉iframe的子項(關閉iframe中的按鈕)的函數。您可以通過調用做到這一點父

parent.myfunction() //call myfunction from parent 

而且在父母的代碼,你必須執行關閉邏輯

myfunction() { 
    iframe.hide() //or whatever 
    } 
+0

只有在父網站的起源和在Iframe中加載的網站的起源相同時,它才能起作用。 – Learnquick

+0

是的,在兩個網站中都放了document.domain ='same.domain' –