Created
May 16, 2024 17:52
-
-
Save johnfmorton/639451fea75d84a5b89b5bcacb6ae8bb to your computer and use it in GitHub Desktop.
Example script to get a YouTube video to display on a page that has an embed
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
<script> | |
document.addEventListener('DOMContentLoaded', (event) => { | |
// Find all oembed elements | |
const oembedElements = document.querySelectorAll('oembed[url]'); | |
oembedElements.forEach(element => { | |
const url = element.getAttribute('url'); | |
const videoId = extractYouTubeId(url); | |
if (videoId) { | |
// Create the iframe element for YouTube | |
const iframe = document.createElement('iframe'); | |
iframe.setAttribute('src', `https://www.youtube.com/embed/${videoId}`); | |
iframe.setAttribute('width', '560'); // Set width | |
iframe.setAttribute('height', '315'); // Set height | |
iframe.setAttribute('frameborder', '0'); | |
iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture'); | |
iframe.setAttribute('allowfullscreen', true); | |
iframe.title = "YouTube video player"; | |
// Replace the oembed element with the iframe | |
element.parentNode.replaceChild(iframe, element); | |
} | |
}); | |
// Function to extract the YouTube video ID from various URL formats | |
function extractYouTubeId(url) { | |
const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/; | |
const matches = url.match(regex); | |
return matches ? matches[1] : null; | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment