如何根据 iframe 内容从父 window 触发事件?

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 文件末尾添加一些脚本来访问父 window (main.html),例如:

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

但不幸的是,它没有用。

我尝试做的另一件事是将 setInterval(check_iframe, 5000) at parent window(main.html) 设置为每隔 5 秒在 iframe 上检查 widget-status-div div,但问题是我无法以某种方式检查 iframe 的内容(或也许我做错了)。

如有任何帮助,我们将不胜感激。

谢谢

由于同源策略,这很可能会失败。它限制 JavaScript 从一种协议和域到另一种协议和域的访问。

有关这方面的更多信息,您可以查看 wiki entry

要实现跨源通信,您可以使用 API 定义的消息传递 here

有了这个 api,您可以在一个文件上定义一个事件侦听器,在另一个文件上定义一个触发器。

收听消息:

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

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

  // ...
}

Post 给另一个文件的消息:

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 Documentation

中查看完整示例