How to check if iframe is loaded or it has a content?
Try this.
<script>function checkIframeLoaded() { // Get a handle to the iframe element var iframe = document.getElementById('i_frame'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Check if loading is complete if ( iframeDoc.readyState == 'complete' ) { //iframe.contentWindow.alert("Hello"); iframe.contentWindow.onload = function(){ alert("I am loaded"); }; // The loading is complete, call the function we want executed once the iframe is loaded afterLoading(); return; } // 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(){ alert("I am here");}</script><body onload="checkIframeLoaded();">
kindly use:
$('#myIframe').on('load', function(){ //your code (will be called once iframe is done loading)});
Updated my answer as the standards changed.
I had the same issue and added to this, i needed to check if iframe is loaded irrespective of cross-domain policy. I was developing a chrome extension which injects certain script on a webpage and displays some content from the parent page in an iframe. I tried following approach and this worked perfect for me.
P.S.: In my case, i do have control over content in iframe but not on the parent site. (Iframe is hosted on my own server)
First:
Create an iframe with a data-
attribute in it like (this part was in injected script in my case) <iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>
Now in the iframe code, use :
var sourceURL = document.referrer;window.parent.postMessage('1',sourceURL);
Now back to the injected script as per my case:
setTimeout(function(){ var myIframe = document.getElementById('myiframe'); var isLoaded = myIframe.prop('data-isloaded'); if(isLoaded != '1') { console.log('iframe failed to load'); } else { console.log('iframe loaded'); }},3000);
and,
window.addEventListener("message", receiveMessage, false);function receiveMessage(event){ if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons { console.log('URL issues'); return; } else { var myMsg = event.data; if(myMsg == '1'){ //8-12-18 changed from 'data-isload' to 'data-isloaded $("#myiframe").prop('data-isloaded', '1'); } } }
It may not exactly answer the question but it indeed is a possible case of this question which i solved by this method.