+2

Vanilla JS: Get Youtube Thumbnail

1. Yêu cầu

Chắc hẳn nhiều bạn đã từng click vào xem một video trên youtube chỉ vì ảnh thumbnail đó hấp dẫn đúng không? Yêu cầu bài toán hôm nay là người dùng nhập link một video youtube vào ô input, khi click vào button View bên cạnh thì hiện ảnh thumbnail của video này lên. Đây là một trong những bài tập vanilla Javascript ở mức cơ bản giúp các bạn làm quen, chủ yếu giải thích về JavaScript nên phần giao diện sẽ không phân tích nhiều. Hi vọng với bài tập này các bạn sẽ thấy thích thú khi học JavaScript.

Youtube Thumbnail

2. Giao diện HTML - CSS

  • Tạo giao diện đơn giản
  • Một ô input để người dùng paste link youtube video vào đó
  • Một button submit
  • Một khu vực hiển thị ảnh thumbnail lấy được
<!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/bootstrap@5.3.3/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>
    // JavaScript here
  </script>
</body>

</html>

3. Hướng giải quyết chính

  • Step 1: Lấy link video youtube trong input
  • Step 2: Lắng nghe sự kiện click ở button View
  • Step 3: Từ link youtube ta sử dung regex để tách lấy ID của video đó
  • Step 4: Gọi sang API của youtube để lấy thumbnail
  • Step 5: Hiển thị

4. JavaScript

<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 extractVideoId(url) {
    const regex = /(?:https?:\/\/)?(?:www\.)?youtube\.com\/(?:watch\?v=|shorts\/)([\w-]{11})/;
    const match = url.match(regex);
    return match ? match[1] : null;
  }

  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');
  }
</script>

5. Kết quả


Bài viết đến đây là hết, hi vọng với bài viết này các bạn đã thêm được nhiều kiến thức bổ ích. Hẹn gặp lại các bạn ở bài viết tiếp theo!


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.