'Angular youtube player not displaying videos when app is deployed

guys! Ran into interesting behaviour when using angular youtube player(ngx-youtube-player ). The video displays perfectly fine when app is running on localhost, but when deployed app is running, video simply doesn't show up in the component. Console shows error Refused to load the script 'https://www.youtube.com/iframe_api' because it violates the following Content Security Policy directive: "script-src-elem 'self' 'unsafe-inline' https://apis.google.com/". We tried to fix it by adding the following line to our index.html

<meta http-equiv="Content-Security-Policy" content="frame-src youtube.com www.youtube.com;">

but it didn't work. I also noticed that this behaviour is observed only in chrome, in Safari everything is working.

We also tried a different way, by adding script-src 'self' youtube.com to meta tag instead, but it throws Refused to load the script 'https://www.youtube.com/iframe_api' because it violates the following Content Security Policy directive: "script-src 'self' youtube.com". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

The code looks like this:

import { Component, OnInit, ViewChild } from "@angular/core";
import { BsModalRef } from "ngx-bootstrap";

@Component({
  selector: "app-video-event",
  templateUrl: "./video-event.component.html",
  styleUrls: ["./video-event.component.css"],
})
export class VideoEventComponent implements OnInit {
  videoId: string;
  link: string;

  constructor(public bsModalRef: BsModalRef) {}

  ngOnInit(): void {
    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    document.body.appendChild(tag);

    const videoUrl = new URL(this.link);

    this.videoId = new URLSearchParams(videoUrl.search.slice(1)).get("v");
  }
}
<div class="modal-body">
    <youtube-player class="youtube-player" [videoId]="videoId"></youtube-player>
 </div>

Any suggestions on how it can be fixed? It appears that it's a problem with CSP and/or iframe, but I can't find anything helpful apart from solutions already tried.



Solution 1:[1]

Problem is with the way you get that videoid from url parameter. you add that link variable but there is no link.

       const tag = document.createElement('script');
      tag.src = 'https://www.youtube.com/iframe_api';
      document.body.appendChild(tag);

      const params = new URL('https://www.youtube.com/watch?v=A-jw5BXS9SU').searchParams;
      const vid = params.get('v');
      if (vid) {
        this.videoId = vid;
      }
    <youtube-player
          [videoId]="videoId"
          [height]="300"
          [width]="540"
        ></youtube-player>

Problem is that

"link" in ts

this works for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Viraj Sandaruwan