Blog

Create a script to play YouTube videos from different channels using the YouTube Iframe Player API

Create a script that plays YouTube videos listed in order within an HTML file, you can use the YouTube Iframe Player API along with some JavaScript code. Below is a sample HTML file with embedded JavaScript that accomplishes this task.

you can load videos from your YouTube channel dynamically into your webpage using the YouTube Data API. This allows you to retrieve a list of videos from your channel and then embed them into your webpage.

want to play videos from multiple YouTube channels or video links collected from different sources, you can still achieve that by creating an array of video IDs and playing them sequentially using the YouTube Iframe Player API. 

To use the YouTube Iframe Player API, you simply need to include a script tag in your HTML file that loads the API asynchronously from YouTube's servers. You don't need to download or install anything separately. Here's how you include the YouTube Iframe Player API in your HTML file.

# Explanation of <iframe> and YouTube video's <URL link> : Here an example link:

<iframe width="560" height="315" src="https://www.youtube.com/embed/4S0EaSKDgJY?si=89m-ge71wfG3JlSq" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>


# Explanation this "iframe" & of this "URL" :

  1. src: This attribute specifies the source URL of the embedded content. In this case, it's a YouTube video player. The URL is :  https://www.youtube.com/embed/4S0EaSKDgJY?si=89m-ge71wfG3JlSq . Let's break down this URL:
    1. https://www.youtube.com/embed/: This is the base URL for embedding YouTube videos.
    2. 4S0EaSKDgJY: This part of the URL is the unique identifier for the embedded YouTube video. It's the video ID.
    3. ?si=89m-ge71wfG3JlSq: This part of the URL appears to be a query parameter, si, with the value P3_62rN158yzB1ml. This parameter is a tracking or session identifier specific to this embed request. It's not a standard part of the YouTube embed URL.
  2. title: This attribute specifies the title of the embedded content, which in this case is "YouTube video player".
  3. frameborder: This attribute specifies whether or not to display a border around the iframe. In this case, it's set to 0, meaning no border will be displayed.
  4. allow: This attribute specifies a set of permissions for the iframe. In this case, it allows certain actions like accelerometer, autoplay, clipboard-write, encrypted-media, gyroscope, and picture-in-picture.
  5. referrerpolicy: This attribute specifies the referrer policy for the iframe content. In this case, it's set to "strict-origin-when-cross-origin", which means that the full referrer will be sent when navigating to or requesting the iframe content from the same origin, but only the origin will be sent when making cross-origin requests.
  6. allowfullscreen: This attribute specifies whether the iframe can be displayed in full-screen mode. In this case, it's allowed.


-------------------------------

# Apply The code: create an index.html file and copy this code past in your HTML file 

-------------------------------

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>NetKib:Web Developer</title>

</head>

<body>

    <div id="player"></div>


    <!-- i collected video IDs from this iframe, checke here:

    <iframe width="560" height="315" src="https://www.youtube.com/embed/4S0EaSKDgJY?si=89m-ge71wfG3JlSq" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

    <iframe width="560" height="315" src="https://www.youtube.com/embed/jr3efMqSUyo?si=e2qxWktoaVdEhaUL" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

    <iframe width="560" height="315" src="https://www.youtube.com/embed/iOrxZiDd8v0?si=KjMWVNdIPV24aNsj" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

    -->


    <script>

        // List of YouTube video IDs

        var videoList = [

            "4S0EaSKDgJY",

            "jr3efMqSUyo",

            "iOrxZiDd8v0"

            // Add more video IDs as needed

        ];


        var player;

        var currentIndex = 0;


        // Function to create YouTube player

        function onYouTubeIframeAPIReady() {

            player = new YT.Player('player', {

                height: '360',

                width: '640',

                videoId: videoList[currentIndex],

                events: {

                    'onReady': onPlayerReady,

                    'onStateChange': onPlayerStateChange

                }

            });

        }


        // Function called when player is ready

        function onPlayerReady(event) {

            event.target.playVideo();

        }


        // Function called when player state changes

        function onPlayerStateChange(event) {

            if (event.data === YT.PlayerState.ENDED) {

                // Play next video when current video ends

                currentIndex++;

                if (currentIndex < videoList.length) {

                    player.loadVideoById(videoList[currentIndex]);

                } else {

                    // End of video list, you can add any desired behavior here

                    console.log("End of video list");

                }

            }

        }


        // Load YouTube Iframe API asynchronously

        var tag = document.createElement('script');

        tag.src = "https://www.youtube.com/iframe_api";

        var firstScriptTag = document.getElementsByTagName('script')[0];

        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    </script>

</body>

</html>


-------------------------------

Here I explained about the <script>:

This script is responsible for playing a sequence of YouTube videos embedded in an HTML page. Let's break down what each part of the script does:

  1. videoList: This is an array containing the YouTube video IDs that you want to play. Each element of the array represents a unique video ID.
  2. player and currentIndex: These variables are used to keep track of the currently playing video and the index of the next video to play in the videoList.
  3. onYouTubeIframeAPIReady(): This function is a callback function that is called automatically when the YouTube Iframe API is ready to be used. Inside this function, a new YouTube player (player) is created using the YT.Player constructor. The constructor takes an element ID (in this case, 'player'), height, width, initial video ID (taken from videoList[currentIndex]), and event handlers.
  4. onPlayerReady(event): This function is an event handler that is called when the YouTube player is ready. In this script, it immediately starts playing the first video in the list using event.target.playVideo().
  5. onPlayerStateChange(event): This function is another event handler that is called when the state of the YouTube player changes. It checks if the video has ended (event.data === YT.PlayerState.ENDED) and if so, increments the currentIndex to move to the next video in the list. If there are more videos to play, it loads the next video using player.loadVideoById(videoList[currentIndex]). If it reaches the end of the videoList, it logs a message to the console indicating that it has reached the end of the video list.
  6. Asynchronous loading of YouTube Iframe API: This part of the script dynamically creates a <script> element and sets its src attribute to the URL of the YouTube Iframe API ("https://www.youtube.com/iframe_api"). Then it inserts this script tag into the HTML document before the first script tag found in the document. This ensures that the YouTube Iframe API is loaded asynchronously and available for use.

Overall, this script sets up a YouTube player to play a sequence of videos specified in the videoList array, and it handles the transition between videos automatically.


-------------------------------

# You can add more player_parameters:

https://developers.google.com/youtube/player_parameters

 playerVars: {                                           


// Height of the player                                          

height: '360',


// Width of the player                                                                      

width: '640', 


// Autoplay the video (1 = true, 0 = false)           

autoplay: 1,                 


// Language preference for closed captions            

cc_lang_pref: 'en',               


// Show closed captions by default (1 = true, 0 = false)    

cc_load_policy: 1,   


// Color of the video progress bar                    

color: 'red',                 


// Show video controls (1 = true, 0 = false)          

controls: 1,                   


// Disable keyboard controls (1 = true, 0 = false)    

disablekb: 0,             


// Enable the JavaScript API (1 = true, 0 = false)    

enablejsapi: 1,           


// End playing the video at a specified time (in seconds)   

end: 120,             


// Allow fullscreen playback (1 = true, 0 = false)    

fs: 1,                     


// Interface language for the player                  

hl: 'en',                 


// Show video annotations (1 = true, 3 = false)        

iv_load_policy: 3,         


// ID of a playlist or search results list to play      

list: 'YOUR_PLAYLIST_ID',


// Type of list specified by the 'list' parameter      

listType: 'playlist',     


// Loop the video (1 = true, 0 = false)               

loop: 0,                   


// Show minimal YouTube branding (1 = true, 0 = false)       

modestbranding: 1,   


// Domain that the player's API requests should originate from                       

origin: 'http://example.com',


// Comma-separated list of video IDs to create a playlist                        

playlist: 'VIDEO_ID_1,VIDEO_ID_2' ,


// Play video inline on supported mobile devices (1 = true, 0 = false)           

playsinline: 1 ,        


// Show related videos at the end of playback (1 = true, 0 = false)      

rel 0,           


// Start playing the video at a specified time (in seconds)        

start: 30,             


// URL that refers to the current page     

widget_referrer: 'http://example.com',  


// Add more player parameters as needed                                          

}