Search code examples
htmliframeyoutubeyoutube-iframe-api

Is there a way for Embeded Youtube videos to play only once?


I'd like for my YouTube video to only be allowed to play once. Is this possible? I'm working with iframe and haven't been able to find anything online. I would appreciate any help on this!


Solution

  • Yes, you can do it. read the iframe api it has a lot of useful functions and variables.

    I don't know if you can get the iframe element if it's made in the html but you can make it via Javascript like the API shows.

    here's an example of what you are seeking, the iframe doesn't seem to work in the stack snippet. here is a demo : https://jsfiddle.net/215mekhd/

    you can also hide the controllers using : playerVars: { 'controls': 0 }, inside the settings object of the second YT.Player parameter.

       
          // 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_id', {
              height: '390',
              width: '640',
              videoId: 'fUXdrl9ch_Q',
              playerVars: {
                'playsinline': 1
              },
              events: {
                'onStateChange': onPlayerStateChange
              }
            });
          }
    
          
          function onPlayerStateChange(event) {
            if (event.data == 0) {
              player.destroy();
            }
          }
         
        
    <html>
      <body>
        <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
        <div id="player_id">this will be replaced with a video</div>
    
      </body>
    </html>