How do I update an iframe url?

I am creating an application using ionic in which I am displaying a url using an iframe. This is the HTML code:

  <iframe id="myFrame" width="100%" height={{iframeHeight}}>

      

This is angular js:

 $scope.iframeHeight = window.innerHeight;
                        document.getElementById("myFrame").src = value['url'];

      

Everything works, however, when I make changes to the site from the backend and update the application, the new changes do not appear in the application.

+3


source to share


3 answers


What you are doing in your code is not a valid way. You manipulate the DOM with a custom method that won't start the digest loop, you need to start it manually by executing $scope.$apply()

. This will fix your problem, but generally you shouldn't be doing DOM controller manipulation, which is considered BAD practice. Rather, I suggest you use angular's two way binding function. Assign the url in a scope variable and add this to the iframe tag with ng-src="{{url}}"

so that the src

url will be updated by angular and as the url is updated iframe

will load the content from the src

url in it.

Html

<iframe id="myFrame" width="100%" ng-src="{{url}}" height={{iframeHeight}}>

      

code

$scope.url = "http://example.com"

      



As you change the scope variable in the controller, the value of the src

iframe will also change and iframe

reload the content.

Update

To solve the caching problem, you need to add the current time to your url, which will generate a new url every time and it will not be cached by the browser. Something like $scope.url = "http://example.com?dummyVar="+ (new Date()).getTime()

, using this, it will never hurt your current behavior, only you need to add dummyVar

with the current time value, which would always be unique.

$scope.url = "http://example.com?dummyVar="+ (new Date()).getTime()

      

+7


source


As @pankajparkar suggested in his answer, I suggest you use angular two way data binding.

In addition to this, you need to wrap the urls $sce.trustAsResourceUrl

for your iframe to work.

<iframe id="myFrame" width="100%" ng-src="{{url}}" height={{iframeHeight}}>

      



and

$scope.url = $sce.trustAsResourceUrl("http://example.com");

      

+1


source


The update didn't work for me with a timestamp like in Pankaj Parkar's answer, so I solved it in a slightly hacky way that just toggles ng-if on and off and forces the iframe to load again.

Template:

<iframe ng-if="!vm.isRefreshing"></iframe>

      

Controller:

refreshIframe() {
    this.isRefreshing = true;

    $timeout(() => {
        this.isRefreshing = false;
    }, 50);
}

      

+1


source







All Articles