0

伙计们!使用角度 youtube 播放器 ( ngx-youtube-player ) 时遇到有趣的行为。当应用程序在本地主机上运行时,视频显示非常好,但是当部署的应用程序运行时,视频根本不会显示在组件中。控制台显示错误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/"。我们尝试通过将以下行添加到我们的index.html来修复它

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

但它没有用。我还注意到这种行为仅在 chrome 中观察到,在 Safari 中一切正常。

我们还尝试了另一种方法,script-src 'self' youtube.com改为添加元标记,但它会抛出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.

代码如下所示:

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>

关于如何修复它的任何建议?看来这是 CSP 和/或 iframe 的问题,但除了已经尝试过的解决方案之外,我找不到任何有用的东西。

4

0 回答 0