JS代码拉Youtube直播视频ID



我想创建一个网页,以我频道的直播为特色,同时显示直播聊天。使用针对频道直播的iframe代码src,我能够让网站显示当时正在直播的任何视频:

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

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

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

因此,我正试图使用JS代码从直播iFrame中提取直播视频ID,以便在直播聊天iFrame中使用。使用开发人员控制台,我确定以下代码可以提取视频ID,但由于试图访问跨源iframe,我遇到了一个错误。

代码:(使用从iframe视频中获取youtube视频id的代码和从一个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]);
}

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

错误:

未捕获DOMException:阻止原点为"MY_DOMAIN"的帧访问跨原点帧。

根据我的研究,你可以使用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>

最新更新