How to include YouTube iframe API in Magento 2 layout template?

I'm using Magento v2.4.1 and i want to show a youtube video on my storefront home page and control it using youtube iframe API in .phtml file, how can I correctly load this youtube iframe API in my .phtml file? because I need to include the script file from https://www.youtube.com/iframe_api instead of local dir

reference: https://developers.google.com/youtube/iframe_api_reference

Answers 1

  • Add phtml to Home page using:

    app/design/frontend/{Package}/{theme}/Magento_Theme/layout/cms_index_index.xml

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="content">
                <block class="Magento\Framework\View\Element\Template" name="youtube" template="Magento_Theme::youtube.phtml"/>
            </referenceContainer>
        </body>
    </page>
    

    app/design/frontend/{Package}/{theme}/Magento_Theme/templates/youtube.phtml

    <div id="player"></div>
    
    <script>
      // 2. This code loads the IFrame Player API code 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);
    
      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          playerVars: {
            'playsinline': 1
          },
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
    
      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }
    
      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 6000);
          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>
    

Related Questions