I want to get the channel ID of a user that uploaded a certain YouTube video on javascript to after that comparing the channel id to see if it's in an array.
The thing is, I can't find exactly how to get that from javascript. I tried to get:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=[Video ID]&key=[my key]
but it gives me JSON parsing error on every video. Anyone knows how to do it exactly using YouTube API? Doesn't matter if I have to add an exteral script on the html part.
And, as an example of what I want to do, for this video:
https://www.youtube.com/watch?v=jNQXAC9IVRw
it should return 'UC4QobU6STFB0P71PMvOGN5A'
.
Any idea on how to do it?
I took the Ajax code from youmightnotneedjquery.com and edited it a bit to make a getJSON
utility function. This worked for me:
var API_KEY = 'YOUR_API_KEY'; // Replace this with your own key
getJSON(
'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=jNQXAC9IVRw&key=' + API_KEY,
function (err, data) {
if (err) {
alert(err);
} else {
alert(data.items[0].snippet.channelId);
}
}
);
function getJSON(url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// We have the JSON, now we try to parse it
try {
var data = JSON.parse(request.responseText);
// It worked, no error (null)
return callback(null, data);
} catch(e) {
// A parsing arror occurred
console.error(e);
return callback('An error occurred while parsing the JSON.');
}
}
// If an error occurred while fetching the data
callback('An error occurred while fetching the JSON.');
};
request.onerror = function() {
// There was a connection error of some sort
callback('An error occurred while fetching the JSON.');
};
request.send();
}