Categories
JavaScript Answers

How to get a YouTube thumbnail from a YouTube iframe with JavaScript?

Spread the love

Sometimes, we want to get a YouTube thumbnail from a YouTube iframe with JavaScript.

In this article, we’ll look at how to get a YouTube thumbnail from a YouTube iframe with JavaScript.

How to get a YouTube thumbnail from a YouTube iframe with JavaScript?

To get a YouTube thumbnail from a YouTube iframe with JavaScript, we can create the URL with the video ID and quality setting.

For instance, we write

const getYoutubeThumbnail = (url, quality) => {
  if (url) {
    let videoId, thumbnail, result;
    result = url.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/);
    if (result) {
      videoId = result.pop();
    }
    result = url.match(/youtu.be\/(.{11})/);
    if (result) {
      videoId = result.pop();
    }

    if (videoId) {
      if (typeof quality === "undefined") {
        quality = "high";
      }

      let qualityKey = "maxresdefault";
      if (quality === "low") {
        qualityKey = "sddefault";
      } else if (quality == "medium") {
        qualityKey = "mqdefault";
      } else if (quality == "high") {
        qualityKey = "hqdefault";
      }

      const thumbnail = `http://img.youtube.com/vi/${videoId}/${qualityKey}.jpg`;
      return thumbnail;
    }
  }
  return false;
};

to define the getYoutubeThumbnail function.

In it, we get the videoId from the YouTube urlwithmatch`.

We match the patterns for YouTube URLs to get the videoId.

Then we get the qualityKey to get the image file name according to the thumbnail quality.

And then we put the image thumbnail URL together.

Conclusion

To get a YouTube thumbnail from a YouTube iframe with JavaScript, we can create the URL with the video ID and quality setting.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *