0

I am working on a chrome extension that was utilizing the google search api, to return an image from an ajax request. Apparently the api is no longer functional, so I was wondering how I could make a similar request with the Custom Search Element Api. I have pasted the portion of my code that was making the request below.

var logo = function (searchTerm, callback, message, name) {
    var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images'     +
        '?v=1.0&q=' + encodeURIComponent(searchTerm);
    var x = new XMLHttpRequest();
    x.open('GET', searchUrl);

    // The Google image search API responds with JSON, so let Chrome parse it.
    x.responseType = 'json';

    x.onload = function() {
        // Parse and process the response from Google Image Search.
        var response = x.response;
        if (!response || !response.responseData || !response.responseData.results ||
            response.responseData.results.length === 0) {
            console.log( "loading error" )
            console.log(response)
            console.log(response.responseData)
            console.log(response.responseData.results)
        }
        var firstResult = response.responseData.results[0];
        // Take the thumbnail instead of the full image to get an approximately
        // consistent image size.
        var imageUrl = firstResult.tbUrl;
        var width = parseInt(firstResult.tbWidth);
        var height = parseInt(firstResult.tbHeight);

        console.assert(
            typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
            'Unexpected respose from the Google Image Search API!');
        callback(imageUrl, width, height, message, name);
    };
    x.onerror = function() {
      alert("error")
         document.writeln("network error");
    };
    x.send();
}

I have been trying to figure it out by reading the the documentation, but I could definitely use some help.

john dith
  • 51
  • 6

1 Answers1

1

Here's the link of the docs: Using REST.

You need to create your own Custom Search Engine on google developer console, modify the getImageUrl() method accordingly.

change searchUrl

var searchUrl = 'https://www.googleapis.com/customsearch/v1?' +
    'key=' + 'YOUR_KEY' +
    '&cx=' + '00000:yourcx' +
    '&searchType=image' +
    '&q=' + encodeURIComponent(searchTerm);

and modify the response object according to the JSON.

You can refer to this question for how to tweak the console and refine search result.

Community
  • 1
  • 1
J.Zhang
  • 146
  • 14