1
/* eslint-env browser */
4
// Please register for your own YouTube API key!
5
// https://developers.google.com/youtube/v3/getting-started#before-you-start
6
const API_KEY = 'AIzaSyC4trKMxwT42TUFHmikCc4xxQTWWxq5S0g';
7
const API_URL = 'https://www.googleapis.com/youtube/v3/search';
9
function serializeUrlParams(params) {
10
return Object.keys(params).map(key => {
11
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
15
function youtubeSearch(searchTerm, maxResults) {
18
maxResults: maxResults,
24
let url = new URL(API_URL);
25
url.search = serializeUrlParams(params);
27
return fetch(url).then(response => {
29
return response.json();
31
throw new Error(`${response.status}: ${response.statusText}`);
32
}).then(function(json) {
37
document.querySelector('#search').addEventListener('submit', event => {
38
event.preventDefault();
40
var results = document.querySelector('#results');
41
while (results.firstChild) {
42
results.removeChild(results.firstChild);
45
let searchTerm = document.querySelector('#searchTerm').value;
46
let maxResults = document.querySelector('#maxResults').value;
48
youtubeSearch(searchTerm, maxResults).then(videos => {
49
videos.forEach(video => {
50
let img = document.createElement('img');
51
img.src = video.snippet.thumbnails.medium.url;
52
results.appendChild(img);
54
}).catch(error => console.warn('YouTube search failed due to', error));