user386430
user386430

Reputation: 4967

How to check iframe is loaded in JavaScript

I am loading in an iframe which takes some time to load. I need to check that the iframe has loaded completely and get the height of it

Can anybody tell how to how to check iframe is loaded in JavaScript?

Upvotes: 1

Views: 5458

Answers (3)

Seth
Seth

Reputation: 10454

In JavaScript, the script, img, and iframe tags all support a load event.

You can leverage it in vanilla JS, which is already answered, with either:

document.getElementById('#my-iframe').addEventListener('load', function () { ... });

document.getElementById('#my-iframe').onLoad = function() { ... };

But if you need an example of how to implement this in Angular specifically, you can do so in the controller or inside a directive's link function by using the element argument.

In a controller:

myApp.controller('SomeController', ['$scope', function($scope) {
  var iframe = angular.element('#my-iframe');
  iframe.on('load', function() {
    console.log(iframe.height());
  });
}]);

In a directive:

myApp.controller('SomeController', ['$scope', function($scope) {
  $scope.foo = 'bar';
}])
.directive('myDirective', ['$interval', function($interval) {
  function link(scope, element, attrs) {
    var iframe = element.find('#my-iframe');
    iframe.on('load', function() {
      $interval(function() {
        console.log(iframe.height();
      }, 1000);
    });
  }

  return {
    link: link
  };
}]);

Upvotes: 1

gaetanoM
gaetanoM

Reputation: 42054

In javascript you may listen on DOMContentLoaded, the jQuery equivalent of document ready, and so add the event listener onload to the iframe:

document.addEventListener("DOMContentLoaded", function(e) {
  document.getElementById('ifrm').addEventListener('load', function(e) {
    document.body.innerHTML += '<p>Iframe loaded</p>';
  }, false);
});
<iframe id='ifrm' src="https://www.wikipedia.org/"></iframe>

Upvotes: 0

Mahesh Chavda
Mahesh Chavda

Reputation: 593

You can use jQuery's load method to load iFrame and then in the callback get the contents of that. And depending on the content of the iFrame you can make further decision.

$('#iFrame').load(cbLoaded);

function cbLoaded()
{
   var doc = $('#iFrame').contents()[0].documentElement;
   // Get contents here:
   var content = doc.innerText || doc.textContent;
}

Upvotes: 1

Related Questions