YouTube Videos through videoID

I am having trouble getting my video to play even though I am fetching the correct videoID. Am I supposed to use the YouTube feature or should I use something else? Here is my code:

function fetchTrailer() {
    // Get the movie title from iniMovieTitle
    let movieTitle = iniMovieTitle.value

    // Set up the YouTube API request URL, using user input for the movie title
    let apiKey = "AIzaSyBQVoRl6mpmh89zNs10LNOu-8tUfs1HqGs" // My YouTube API key
    let url = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(movieTitle)} Trailer&maxResults=1&key=${apiKey}&order=viewCount&type=video`

    // Make the API request
    fetch(url)
        .then(response => response.json()) // Parse the JSON response
        .then(data => {
            // Check if there are results
            if (data.items && data.items.length > 0) {
                // Get the video ID from the response
                let videoId = data.items[0].id.videoId
                console.log("Fetched video ID:", videoId)
                
                // Set the src property of vdPlayer to the YouTube embed URL
                ytPlayer.videoID = videoId
            } else {
                console.log("No trailers found for this movie.")
            }
        })
        .catch(error => console.error("Error fetching video ID:", error))
}

// Trigger the trailer search on button click
btnSearchTrailer.onclick = function() {
    fetchTrailer() // Call the fetchTrailer function
}

Tip : If you’re pasting code, html or config files, surround the code with triple back ticks (```), before the first line and after the last one. It will be formatted properly. (We fixed it for you this time)

How are you running this?

It won’t work (due to security reasons) if you use Start in Desktop Browser. It should work if you use Deploy to a Local Folder which sets up a web server or if you deploy it to a web server.

There’s a YouTube sample you can try.