3

I am using Angular 5, and fairly new to TypeScript and Angular. I know how to call a function from regular button from my x.component.html after clicking, but, couldn't find how to call a function from iFrame.

My component.html code :-

<iframe id="myIframe" src="{{getSanURL()}}" name="targetframe" height="100%" allowTransparency="true" width="100%" scrolling="yes" frameborder="0" >
   
 </iframe>

My component.ts code :-

public getSanURL()
    {      
     var nd = new Date(); 
     var Day = nd.getUTCDate();
     var Month = nd.getUTCMonth()+1;
     
     var str = new String(currentUTCYear);
    
     var DM = Day.toString()+Month.toString();
     console.log(DM);
     
     var dynamicSanURL = "https://somelink"+DM+".someaddress/Some.html"; 
  
     return dynamicSanURL;
   }

Took help from this but in vain - JavaScript function in iframe src

I want this dynamicSanURL to be returned in iFrame. I don't know where I am going wrong.

Ravish Rawat
  • 476
  • 2
  • 15
  • 48

1 Answers1

1

I think you also have an error about unsafe url value in your console. It is a default security procedure in angular. You have to bypass it with DomSanitizer. Also you need to check if the domain you request lets you display iframe with, X-Frame-Options: See Here

In your component.ts

import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
export class AppComponent {
  constructor(private sanitizer: DomSanitizer)
      {
         this.setSafeUrl();
      }
  safeUrl: SafeResourceUrl;
  setSafeUrl(){
     var nd = new Date(); 
     var Day = nd.getUTCDate();
     var Month = nd.getUTCMonth()+1;

     var str = new String(currentUTCYear);

     var DM = Day.toString()+Month.toString();
     console.log(DM);

     var dynamicSanURL = "https://somelink"+DM+".someaddress/Some.html";
     this.safeUrl = `this.sanitizer.bypassSecurityTrustResourceUrl(dynamicSanURL);`
  }
}

Then in your html set safeUrl as src:

<iframe id="myIframe" [src]="safeUrl" name="targetframe" height="100%" allowTransparency="true" width="100%" scrolling="yes" frameborder="0" >

 </iframe>
Okan Aslankan
  • 3,016
  • 2
  • 21
  • 26