In the process of developing a Chrome extension that is intended to extract the YouTube video IDs of the top 3 search results based on an input string, I have encountered a roadblock. The current code snippet looks like this:
var items = [];
function getVideo(searchQuery,item){
searchQuery = searchQuery.replace(/ /g,'+');
var queryURL = 'https://www.googleapis.com/youtube/v3/search?q='+searchQuery+'&key=AIzaSyDq5SqWuQIEfIx7ZlQyKcQycF24D8mW798&part=snippet&maxResults=3&type=video';
//console.log(queryURL);
$.getJSON(queryURL,function(data){
items = data.items;
/*for(var i in items){
console.log((items[i].id.videoId).toString());
}*/
});
}
document.addEventListener('DOMContentLoaded',function(){
var button = document.getElementById('search');
var div = document.getElementById('results');
button.addEventListener('click',function(){
var base_url = 'https://www.youtube.com/watch?v=';
var url = [];
var input = document.getElementById('input');
var result = input.value;
getVideo(result);
for(var i in items){
console.log(items[i].id.videoId.toString());
//$('<p>'+(items[i].id.videoId.toString())+'</p><br>').appendTo('#results');
//url.push(base_url+items[i].id.videoId.toString());
}
/*for(var j in url){
console.log("test");
console.log(url[j]);
$('<p>'+url[j]+'</p><br>').appendTo('#results');
}*/
});
});
Upon execution in its current form, there is no output in the console. Strangely, making a minor adjustment resolves the issue.
var items = [];
function getVideo(searchQuery,item){
searchQuery = searchQuery.replace(/ /g,'+');
var queryURL = 'https://www.googleapis.com/youtube/v3/search?q='+searchQuery+'&key=AIzaSyDq5SqWuQIEfIx7ZlQyKcQycF24D8mW798&part=snippet&maxResults=3&type=video';
//console.log(queryURL);
$.getJSON(queryURL,function(data){
items = data.items;
for(var i in items){
console.log((items[i].id.videoId).toString());
}
});
}
document.addEventListener('DOMContentLoaded',function(){
var button = document.getElementById('search');
var div = document.getElementById('results');
button.addEventListener('click',function(){
var base_url = 'https://www.youtube.com/watch?v=';
var url = [];
var input = document.getElementById('input');
var result = input.value;
getVideo(result);
/*for(var i in items){
console.log(items[i].id.videoId.toString());
//$('<p>'+(items[i].id.videoId.toString())+'</p><br>').appendTo('#results');
//url.push(base_url+items[i].id.videoId.toString());
}*/
/*for(var j in url){
console.log("test");
console.log(url[j]);
$('<p>'+url[j]+'</p><br>').appendTo('#results');
}*/
});
});
The only alteration made was moving the console.log statement within the function getVideo. Since 'items' is a globally scoped variable, the issue of scope should not arise. What could be causing this unexpected behavior?