HoumyM
HoumyM

Reputation: 25

Embed YouTube video based on results from API

I am trying to embed YouTube videos into a webpage using the YouTube API. So far I have been able to use the API to gather results based on the search criteria "dog". How would I go about taking those results and turning them into embedded videos. Right now I am getting the results appearing as a JSON file on a index.html page. Also, this only works when my HTML and JavaScript files are hosted on a server, is there a way of doing this locally?

Would appreciate your help, and thank you in advance.

HTML:

<html>
    <head>
        <script src="javascript.js" type="text/javascript"></script>
        <script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
    </head>
    <body>
        <pre id="response"></pre>
    </body>
</html>

JavaScript:

function showResponse(response) {
    var responseString = JSON.stringify(response, '', 2);
    document.getElementById('response').innerHTML += responseString;
}

function onClientLoad() {
    gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}

function onYouTubeApiLoad() {
    gapi.client.setApiKey('API_KEY');

    search();
}

function search() {
    var request = gapi.client.youtube.search.list({
        part: 'snippet',
        q:"dogs",

    });


    request.execute(onSearchResponse);
}

function onSearchResponse(response) {
    showResponse(response);
}

Upvotes: 1

Views: 1799

Answers (1)

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17651

  1. To display the videos from your search results, you'll be using the video ID and the iframe html tag. Here's the full instructional video, and the working sample. You need to provide your own API KEY.
  2. Setup a server like nodejs. Since you'll be using localhost, add http://localhost:port_number (8080,etc) to your HTTP refferrer on GDC. If you're http refferer port number is 8080, then your nodejs port number should also be 8080.
  3. Run the project in the URL it should look something like, http://localhost:4567/ViralVideos/index.html. Hope that helps :)

Upvotes: 6

Related Questions