user2024080 user2024080 - 2 months ago 6
HTML Question

How to hear from `iframe` content change?

There is a

angularjs
application, I am working out of it. in my web page, I am getting application loaded in the
iframe
- I just want to know whether the
ifame
loaded or not. for that, I use:

//but i don't like this.

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

myTimeout();


in the
iframe
there is number of content keep loading and changing. But one of the event I would require to add in the element with class name of
.ui-grid-icon-ok
- how can I hear from
document
that the
element existence
- any one help me?

Answer

If there's no constraints CORS or XSS, you should be able to do something like the following.

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>

If there are any constraints (e.g. sandboxing, CORS, XSS, etc.), you'll get an alert dialog every 10th of a second with the error, and I hope you have the ability to click the checkbox to ignore them. :)

Note: This is a modified version of this other stack overflow answer, expanded to demonstrate errors.

Comments