Jan 22, 2016

Implant / inject event function to every (change of src) page in iframe with AngularJs

To inject an event manually with AngularJs (from the outside of child iframe),
you'll need two key things:

  • window.onload()
  • window.onmousedown

You'll need an angular directive to help injecting the event function and iframe page being "load".

// inject touch event to iframe child body
angular.directive('iframe', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      element[0].onload = function() {
        scope.loaded();
      };
    },
    controller: function($scope, $window) {
      $scope.loaded = function() {
        $window.frames[0].window.onmousedown = function() {
          alert('Touched!');
        };
      };
    }
  };
});


Firstly, from element[0], you'll get your iframe element.
2nd, prepare a "loaded()" function to let "link()" to initiate for "onload()".


This solution made by the inspiration from AngularJS: onLoad from an iframe directive by Ashish Datta

No comments:

Post a Comment

Hey, thank you for spending time leaving some thoughts, that would be really helpful as encouragement for us to write more quality articles! Thank you!