Reputation: 1119
I've written a little mobile web application to control YouTube on my PC from my phone, however something strange is happening when searching using the YouTube API. The first time the page loads, everything works great - enter the search term, click search and results are returned.
However, if I click onto another page and then come back, the search no longer works and I see "Uncaught TypeError: Cannot read property of 'search' undefined" in the search function below.
I'm very new to JavaScript so feel free to berate the code, but I've been seeing this problem for a while and despite much googling haven't been able to find a solution.
// Called automatically when JavaScript client library is loaded.
function onClientLoad()
{
//
try
{
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded.
function onYouTubeApiLoad()
{
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
}
function search(q) {
// Create api request and execute it
var request = gapi.client.youtube.search.list({
type: 'video',
part: 'snippet',
q: q
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
function onSearchResponse(response) {
showResponse(response);
}
The link to the API script is in my search.aspx page as below:
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
JQuery is also being used, so I don't know if there is any funny business being caused there but any ideas at this point would be very much appreciated!
Upvotes: 1
Views: 342
Reputation: 1119
Looks like I figured it out. It looks like the initial load of the API is done when it first loads the script in
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
but then not loaded again when leaving and coming back to the page. I added onClientLoad(); to the
$( document ).ready function at it seems to be working now.
Upvotes: 0
Reputation: 79
Make sure you're calling search()
after onYouTubeApiLoad()
executes.
If you are binding search()
to a click event, make sure to do so on the callback:
function onYouTubeApiLoad()
{
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$("button#search").on("click", function(){ search(...); })
}
Upvotes: 1