Categories
JavaScript Answers

How to Disable Related Videos with the YouTube JavaScript API?

Spread the love

To disable related videos with the Youtube JavaScript API, we can set the rel property in the playerVars property to 0.

For instance, we can add the following HTML element for the video player:

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

Then we can write:

const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

window.onYouTubeIframeAPIReady = () => {  
  const player = new window.YT.Player("player", {    
    width: 200,    
    height: 100,    
    videoId: "M7lc1UVf-VE",    
    playerVars: {      
      rel: 0,      
      showinfo: 0,      
      ecver: 2   
    }  
  });
};

to add the YouTube script tag with:

const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Then we set the window.onYouTubeIframeAPIReady to a function that invokes the window.YT.Player constructor with the ID of the element for the player as the first argument.

The 2nd argument is an object with various options like the video width and height and video ID. The playerVars.rel property is set to 0 so that related videos will not be shown.

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 *