簡體   English   中英

如何基於iframe內容從父窗口觸發事件?

[英]How to trigger an event from parent window based on iframe content?

我正在使用iframe創建小部件,並且想在特定事件中隱藏iframe。

假設main.html文件具有:

<div id="my_widget">
  <iframe src="www.mysite.com/main.html" width="50%" frameborder="0" height="550" id="my_iframe">Error uploading the frame.</iframe>
</div>

widget.html文件包含:

<div id="widget-status-div" status="success"></div> 

我試圖在widget.html文件的末尾添加一些腳本來訪問父窗口(main.html),例如:

<script type="text/javascript">       
    setTimeout(function(){
      parent.$("#my_widget").fadeOut(300, function() { parent.$("#my_widget").remove(); });
    }, 3000);       
</script>

但不幸的是,它沒有用。

我嘗試做的另一件事是在父窗口(main.html)上設置setInterval(check_iframe,5000)以每隔5秒在iframe上不斷檢查一次widget-status-div div,但是問題是我無法檢查iframe的內容(或者我做錯了)。

任何幫助將不勝感激。

謝謝

由於相同的原產地政策,這將使大多數禮來失敗。 它限制了JavaScript從一種協議和域到另一種協議和域的訪問。

相同的原產地政策結果

有關此的更多信息,您可以查看Wiki條目

要實現跨源通信,您可以使用此處定義的消息傳遞API。

使用此api,您可以在一個文件上定義一個事件偵聽器,在另一個文件上定義一個觸發器。

聽消息:

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

function receiveMessage(event)
{
  if (event.origin !== "http://example.org:8080")
    return;

  // ...
}

將消息發布到另一個文檔:

var parentWindow = window.parent;

// When the popup has fully loaded, if not blocked by a popup blocker:

// This does nothing, assuming the window hasn't changed its location.
parentWindow.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");

您可以在MDN文檔中簽出完整的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM