Get Youtube Thumbnail
by trung ken
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>YouTube Thumbnail Downloader</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-5">
<div class="text-center">
<div class="row justify-content-center">
<div class="col-6">
<h1 class="">YouTube Thumbnail</h1>
<form class="form" onsubmit="getYouTubeThumbnail(event)">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="YouTube Video URL" id="videoUrl" required>
<button class="btn btn-primary" type="submit">View</button>
</div>
</form>
</div>
</div>
<img class="thumbnail d-none" id="thumbnail" src="#" alt="Thumbnail">
</div>
</div>
<script>
// https://www.youtube.com/watch?v=Fw0eZrj2rwU
// https://www.youtube.com/watch?v=S4Xu6AtX9Qs
// https://www.youtube.com/shorts/xjRbwjIT7DE
const youtubeThumbnail = document.getElementById("thumbnail");
function getYouTubeThumbnail(event) {
event.preventDefault();
const videoUrl = document.getElementById("videoUrl").value;
const videoId = extractVideoId(videoUrl);
if (!videoId) {
alert("Invalid YouTube video URL");
return;
}
const thumbnailUrl = `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`;
youtubeThumbnail.src = thumbnailUrl;
youtubeThumbnail.classList.remove('d-none');
}
function extractVideoId(url) {
const regex = /(?:https?:\/\/)?(?:www\.)?youtube\.com\/(?:watch\?v=|shorts\/)([\w-]{11})/;
const match = url.match(regex);
return match ? match[1] : null;
}
</script>
</body>
</html>