Last active
July 17, 2018 15:26
-
-
Save cecyc/3b6fb5038f8d598fe276a7214340c525 to your computer and use it in GitHub Desktop.
Simple script to request a video from YouTube API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Request to YouTube | |
const API_KEY="" | |
const videoUrl = "https://www.youtube.com/watch?v=" | |
let reqUrl = `https://www.googleapis.com/youtube/v3/search?key=API_KEY&part=snippet&q=${query}&maxResults=25` | |
//Get a random int to pick a random video from the results | |
const getRandomInt = () => { | |
let num = Math.random | |
//maxResults are 25 index 0, get a random number between 0 and 24 | |
return Math.floor(num * 24) | |
} | |
//Get URL of cat videos from YouTube | |
const getUrl = () => { | |
let req = new XMLHttpRequest() | |
req.open("GET", reqUrl, true) | |
req.send() | |
req.onload = () => { | |
if (req.readyState === 4 && req.status === 200) { | |
let res = JSON.parse(req.responseText) | |
//want results to be random | |
let i = getRandomInt() | |
let videoId = res["items"][i]["id"]["videoId"] | |
let url = videoUrl + videoId | |
console.log(url) | |
return url | |
} else { | |
console.log("request got status: " + req.status + "error: " + req.statusText) | |
return defaultUrl | |
} | |
} | |
} | |
getUrl() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment