Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to embed Youtube videos in a Ionic 4 app

I am trying to develop an ionic app that i will be deploying as a pwa in which i want to embed Youtube Videos and display them in a grid. Video links, their titles, and brief descriptions are provided by my Cloud Firestore objects.

Now the problem is that when I am trying to use iframe in ionic app with single url like :

<iframe width="560" height="315" src="https://www.youtube.com/embed/6kqe2ICmTxc" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

then it is working but when I am binding it to my database Video URL, then it is not working. The console is showing that URL is not a safe url.

Now, I know that it can be fixed by using the DomSanitizer but i don't know how to use it for the array of objects that contains the required links.

like image 443
pulkit aggarwal Avatar asked Dec 11 '22 05:12

pulkit aggarwal


1 Answers

Try this,

    trustedVideoUrl: SafeResourceUrl;
    array_of_objects = [{vid_link:"https://youtube.com/lalla"},{vid_link:"https://youtube.com/lalla"}]


    constructor(public navCtrl: NavController,
                private domSanitizer: DomSanitizer) {}

    ionViewWillEnter(): void {
      for(let i of array_of_objects){
        i.trustedVideoUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(i.vid_link);
      }
    }  

and in your HTML,

 <iframe *ngFor="let i of array_of_objects" width="100%" height="315" [src]="i.trustedVideoUrl" frameborder="0" allowfullscreen></iframe>

There is one more thing we need to do in order to make this work on iOS, we need to allow navigation to YouTube urls in our config.xml file by adding the below line:

<allow-navigation href="https://*youtube.com/*"/>
like image 116
Chaitanya Mankala Avatar answered Feb 27 '23 14:02

Chaitanya Mankala