我想要创建一个网页,其中包括我的频道的livestream,但也显示livestream聊天。使用iframe代码src来获取频道livestream,我就可以让该站点显示当时正在直播的任何视频:
src="ID“
然而,使用Youtube聊天iFrame代码,我只能针对特定视频的聊天。
src="域名
因此,我试图使用JS代码从livestream iframe中提取livestream视频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]);
}如果我使用开发者工具手动编辑Youtube的iFrame中包含的内容,这段代码将返回正确的视频ID和URL。当我不手动编辑代码时,它将返回以下错误
错误:
Uncaught :阻止具有原点"MY_DOMAIN“的帧访问跨原点帧。
根据我的研究,您可以使用document.postmessge绕过Youtube上的跨源错误,但是我不知道如何将其实现到我的代码中,或者它是否能够解决我所面临的问题。
如果您能提供任何帮助,我们将不胜感激!
发布于 2020-04-09 16:39:29
一些人进一步认为,iFrames的性质会阻止我访问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>https://stackoverflow.com/questions/61106449
复制相似问题