Created
June 27, 2022 16:30
-
-
Save shaneapen/733dba38c29a05362418362d8aef957f to your computer and use it in GitHub Desktop.
Embed Latest YouTube Video From a Channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<iframe class="latestVideoEmbed" vnum='0' cid="UCBJycsmduvYEL83R_U4JriQ" width="600" height="340" frameborder="0" allowfullscreen></iframe> | |
<iframe class="latestVideoEmbed" vnum='1' cid="UC0xXUfNSFQN3qOmf_G_nT5w" width="600" height="340" frameborder="0" allowfullscreen></iframe> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const requestOptions = { | |
method: 'GET', | |
redirect: 'follow' | |
}; | |
const loadVideo = (iframe) => { | |
const cid = iframe.getAttribute('cid'); | |
const channelURL = encodeURIComponent(`https://www.youtube.com/feeds/videos.xml?channel_id=${cid}`) | |
const reqURL = `https://api.rss2json.com/v1/api.json?rss_url=${channelURL}`; | |
fetch(reqURL, requestOptions) | |
.then(response => response.json()) | |
.then(result => { | |
const videoNumber = (iframe.getAttribute('vnum') ? Number(iframe.getAttribute('vnum')) : 0); | |
const link = result.items[videoNumber].link; | |
const id = link.substr(link.indexOf("=") + 1); | |
iframe.setAttribute("src", `https://youtube.com/embed/${id}?controls=0&autoplay=1`); | |
}) | |
.catch(error => console.log('error', error)); | |
} | |
var iframes = document.getElementsByClassName('latestVideoEmbed'); | |
for (var i = 0, len = iframes.length; i < len; i++) { | |
loadVideo(iframes[i]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment