【问题标题】:How to hear from `iframe` content change?如何从“iframe”内容更改中听到?
【发布时间】:2016-09-27 05:14:38
【问题描述】:

有一个angularjs 应用程序,我正在处理它。在我的网页中,我在iframe 中加载了应用程序 - 我只想知道ifame 是否加载。为此,我使用:

//但我不喜欢这个。

 var myTimeout = function () {
         setTimeout(function(){
             if($('.ssueContentIframe').length > 0 ) {
                  penetrate();
                  return;
             }
             myTimeout();
         }, 10000);
     };

    myTimeout();

iframe 中有许多内容不断加载和更改。但是我需要添加类名为.ui-grid-icon-ok 的元素的事件之一 - 我如何从document 那里听到element existence - 任何人帮助我?

【问题讨论】:

  • 父页面的URL是什么,iframe中的文档是什么?有 CORS、XSS 和其他规则可以防止您出于非常充分的理由进入框架内部或框架之外。如果它们来自相同协议的同一主机,则可以为您提供帮助。但是,函数名称 penetrate 对您的可能性来说并不是一个好兆头。
  • 都是同一个 URL,CORS 什么的都没有问题。
  • penetrate 目前在做什么?定义了吗?
  • 如果您可以编辑在 iframe 中加载的应用程序,则可以使用 postMessage developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
  • @TylerY86 - 这是一个函数。它检查 iframe,一旦 iframe 可用,它就会调用 penetrate() :: 来执行此操作 - 我一直调用 setTimeout

标签: javascript jquery html iframe


【解决方案1】:

如果没有 CORS 或 XSS 约束,您应该可以执行以下操作。

var what = document.getElementById('what');

function checkIframeLoaded() {
  try {
    // Get a handle to the iframe element
    var iframe = document.getElementById('iframe');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    what.appendChild(document.createTextNode("Checking...\n"));

    // Check if loading is complete
    if (iframeDoc.readyState == 'complete') {
      afterLoading();
      return;
    }
  } catch (err) {
    alert(err);
  }
  // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
  window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading() {
  what.appendChild(document.createTextNode("It loaded!\n"));
}

checkIframeLoaded();
iframe {
  width: 100px;
  height: 25px;
}
<iframe id="iframe" src="data:text/plain,"></iframe>
<pre id="what">Not loaded.</pre>

如果有任何限制(例如沙盒、CORS、XSS 等),您将每 10 秒收到一个警告对话框,显示错误,我希望您能够单击复选框以忽略它们. :)

注意:这是this other stack overflow answer 的修改版本,已扩展以演示错误。

【讨论】:

  • 修复了一些copypasta;有“iframe”,我应该有“什么”。
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多