我希望创建一个既包含 channel 的直播内容又显示直播聊天内容的网页。使用针对 channel 直播的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]);
}
如果我使用开发人员工具手动编辑Youtube iFrame中包含的内容,则此代码将返回正确的视频ID和URL。当我不手动编辑代码时,它返回以下错误
错误:
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>
关于javascript - JS代码提取Youtube Livestream视频ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61106449/