1

I am trying to set the iframe content height through angular

I have something like

app.controller('testCtr' ['$scope', '$window' ), function() {
   var newWin = $window.open();
   newWin.document.write("<iframe id='iframe' width='100%' height='100%' 
   src='http://www.yahoo.com'></iframe>");

   var iframe = newWin.document.getElementById('iframe');
   iframe.addEventListener('load', function() {                    

       //after iframe is loaded, I want to set the hight of the contents here
       var t =  iframe.contentWindow.document.body.offsetWidth;              

       //console.log(t)  -> return undefined.   

       iframe.contentDocument.body.scrollWidth = '500px';
       iframe.contentDocument.body.scrollHeight = '500px';
   })
}])

How do I accomplish this?

Huangism
  • 16,278
  • 7
  • 48
  • 74
FlyingCat
  • 14,036
  • 36
  • 119
  • 198

1 Answers1

0

The issue you are having is that scrollWidth and scrollHeight are read-only properties.

Also keep in mind you will run into cross origin issues if you try to iframe yahoo.com unless you actually are an engineer at Yahoo.

I recommend you to read this great Q&A, I bet it will give you a better understanding, and maybe you will even avoid having the the issue of iframes in your site. Yet Another cross-domain iframe resize Q&A

However, It's not a proper answer if I don't include an example. You can set the iframe width and height easily using javascript though CSS clases are prefered to keep your code clean.

var app = angular.module('testApp', []);

app.controller('testCtrl', ['$scope', function($scope) {

    $scope.resizeMe = function() {
        var r = Math.round(Math.random() * 100) + 200;

        // For reference, this is how you get the original size:
        // $("#myIframe").height($("#myIframe").contents().find("html").height());

        $("#myIframe").width(r);
        $("#myIframe").height(r);
    };
}]);


<div ng-app="testApp">
    <div ng-controller="testCtrl">
        <button ng-click="resizeMe()">Resize!</button>
        <br>
        <iframe id="myIframe" src="http://example.com"></iframe>
    </div>
</div>

Here's the demo: http://jsfiddle.net/6edeaLe1/

Community
  • 1
  • 1
Josue Alexander Ibarra
  • 8,269
  • 3
  • 30
  • 37