How to check whether iframe loads content?

by arnoldo.moen , in category: HTML & CSS , 4 months ago

How to check whether iframe loads content?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months ago

@arnoldo.moen 

There are several ways to check whether an iframe has loaded content:

  1. Using JavaScript: You can use JavaScript to check the content of the iframe. You can check if the iframe has content by accessing the contentDocument property of the iframe element and checking if it is not null or undefined. Here is an example of how you can do this:
1
2
3
4
5
6
7
8
9
var iframe = document.getElementById('myIframe');

iframe.addEventListener('load', function() {
  if (iframe.contentDocument && iframe.contentDocument.body) {
    console.log('iframe loaded content');
  } else {
    console.log('iframe did not load content');
  }
});


  1. Using the onload event: You can also use the onload event of the iframe element to check if the iframe has loaded content. Here is an example of how you can do this:
1
2
3
4
5
6
7
8
<iframe id="myIframe" src="https://example.com"></iframe>
<script>
  var iframe = document.getElementById('myIframe');
  
  iframe.onload = function() {
    console.log('iframe loaded content');
  };
</script>


  1. Checking the complete property: You can also check the complete property of the iframe element to see if the content has been loaded. Here is an example of how you can do this:
1
2
3
4
5
6
7
var iframe = document.getElementById('myIframe');

if (iframe.complete) {
  console.log('iframe loaded content');
} else {
  console.log('iframe did not load content');
}


By using one of these methods, you can check whether an iframe has loaded content.