Search code examples
youtubeembed

Embed a YouTube playlist but play the last video first


How can I embed a YouTube playlist (from a channel I don’t manage) into my own website, but select the last video in the playlist as the one to play first?


Solution

  • This is certainly not as easy as it ought to be. You'd think you could just add an index parameter to the URL, as you can with Vimeo. But no.

    You have to use the PlaylistItems endpoint of the YouTube Data API (yes, by creating a project in Google Cloud Platform and generating an API key) to return a list of all the videos in the playlist, grab the video ID of the last item in the list, then build a URL for your iframe which includes both the video ID and the playlist ID.

    const apiKey = [YOUR_API_KEY]
    const playlistId = 'PL....'
    const urlBase = 'https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=' + playlistId + '&key=' + apiKey
    
    const setIFrameSrc = async () => {
      let data = await fetch(urlBase).then(response => response.json())  // get first page of items
      while (data.nextPageToken)  // are there more items?
        data = await fetch(urlBase + '&pageToken=' + data.nextPageToken).then(response => response.json())  // get next page of items
      const snippet = data.items.pop().snippet  // pop() grabs the last item
      document.getElementById('[YOUR_IFRAME_ID]').src = 'https://www.youtube.com/embed/' + snippet.resourceId.videoId + '?listType=playlist&list=' + playlistId
    }
    setIFrameSrc()