Reputation: 1868
I want to get all of my YouTube subscriptions using the YouTube API. However, Google limits the amount of items that get returned in API calls to 50. If I'm subscribed to 100+ channels, I'm going to have to loop the API calls to get all of them. For now I just want to console.log() them in the "Inspect popup" debug console.
I did a lot of reading on how to do async calls in a loop in Javascript, but all of them were with a basic for()
loop. In the case of using the YouTube Data API, you have to make your API call, then use the nextPageToken
attribute to get the next page.
This is my popup.js
file currently:
$(document).ready(function() {
var ClientID = '[my client id]';
$('#testBtn').click(function() {
chrome.identity.getAuthToken({"interactive": true}, function(token) {
GetInfo(token, "");
});
});
function GetInfo(userToken, pageToken) {
$.ajax({
url: "https://www.googleapis.com/youtube/v3/subscriptions",
type: 'GET',
data: {
part: "snippet",
mine: "true",
nextPageToken: pageToken,
access_token: userToken
},
success: function(data) {
var allIds = "";
$.each(data.items, function(i, item) {
console.log(item.snippet.resourceId.channelId);
});
var nextPageToken = data.nextPageToken;
if (typeof nextPageToken !== 'undefined')
{
GetInfo(userToken, nextPageToken);
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
}
});
I realize that normally you aren't supposed to make API calls in popup.js, but I just want to get this working then I'll move it to a background script.
This code when executed works great the first time; the success function executes and the channel id's are logged. So I know it's not a problem with authentication. However, when the GetInfo()
function is called again in the success
callback, the data
parameter stays the same. So my script just logs the data in the first callback over and over again indefinitely.
I want to say this is a problem with closures in Javascript, but I don't know what the syntax would look like within an ajax call.
If anyone could help, that would be great!
Upvotes: 1
Views: 1414
Reputation: 14657
According to the documentation, the parameter name for the API is pageToken
, not nextPageToken
. Your nextPageToken
param is probably being ignored by the API so you get the first page over and over again. So you should have:
data: {
part: "snippet",
mine: "true",
pageToken: pageToken,
access_token: userToken
},
Upvotes: 3