JS代码拉取Youtube直播视频ID

JS code to pull Youtube Livestream Video ID

我想创建一个网页,其中包含我频道的直播,但也显示直播聊天。使用针对频道直播的 iframe 代码 src,我能够让网站显示当时正在直播的任何视频:

src="https://www.youtube.com/embed/live_stream?channel=MY_CHANNEL_ID"

但是使用 Youtube Chat iFrame 代码,我只能针对特定视频的聊天。

src="https://www.youtube.com/live_chat?v=VIDEO_ID&embed_domain=MY_DOMAIN

因此,我正在尝试使用 JS 代码从直播 iFrame 中提取直播视频 ID,以便在实时聊天 iframe 中使用。使用开发人员控制台,我确定以下代码可以提取视频 ID,但是由于尝试访问跨域 iframe,我 运行 出错了。

代码: (使用 get youtube video id from iframe video & get element from within an iframe 中的代码开发)

var iframe = document.getElementById('live-video');
var livevid = iframe.contentWindow.document.querySelector("link[href^='https://www.youtube.com/watch?v=']").href,
    regExp = /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/,
    videoId = livevid.match(regExp);

if (videoId && videoId[1].length === 11) {
    console.log(videoId[1]);
}

此代码 returns 正确的视频 ID & URL 如果我使用开发人员工具手动编辑包含在 Youtube 的 iFrame 中。当我不手动编辑代码时,returns出现如下错误

错误:

Uncaught DOMException: Blocked a frame with origin "MY_DOMAIN" from accessing a cross-origin frame.

根据我的研究,您可以使用 document.postmessge 绕过 Youtube 上的跨源错误,但我不知道如何将其实现到我的代码中,或者它是否可以解决我面临的问题。

如果您能提供任何帮助,我们将不胜感激!

进一步思考后意识到 iFrame 的性质会阻止我尝试访问其 DOM 内容;所以我与 Youtube API 合作创建了一个解决方法:

/*Access Youtube iframe API*/
<script src="https://www.youtube.com/iframe_api"></script>

/*Insert Livestream Video*/
<iframe id="live-video" src="https://www.youtube.com/embed/live_stream?channel=[MY_CHANNEL_ID]&enablejsapi=1&version=3&origin=[MY_DOMAIN_HERE]" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen enablejsapi="1"></iframe>

/*Basic API code for Youtube videos*/
<script>
  var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('live-video', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}
function onPlayerReady() {
  var url = player.getVideoUrl(); /*Use Youtube API to pull Video URL*/
  var match = url.match(/[?&]v=([^&]+)/); 
  var videoId = match[1]; /*Use regex to determine exact Video URL*/
/*Insert a new iFrame for the livestream chat after a specific div named chatframe*/
  var livevid = document.createElement("iframe");
  livevid.src = 'https://www.youtube.com/live_chat?v=' + videoId + '&embed_domain=[MY_DOMAIN_HERE]'
  livevid.width = '100%';
  livevid.height= '400px';
  document.getElementById("chatframe").appendChild(livevid);
}
    function onPlayerStateChange() {
    }
</script>