Universal Search #2 Google Custom Search Engine

This is the 2nd article in a series that covers the steps to add searching to Ghost, Hexo or any general website using APIs provided by various services.

The latest version of Universal Search is available on Github at https://github.com/artchen/universal-search.

We have covered UI and common logics in the previous article. This time we are going to integrate Google Custom Search Engine.

Get Engine ID

Go to https://cse.google.com. Click the add button.

gcse-01

Go to next. Enter your website domain. Then click the create button.

gcse-02

On the congratulations screen, click Control Panel.

gcse-03

On the control panel, click Search Engine ID, note down the ID in the popup modal.

gcse-04

Get API Key

Go to Google API Console. You may need to register first. Click ENABLE API.

gcse-05

Search for “custom search”, click on the first result.

gcse-06

On the Custom Search API page, click on Credential in the left side bar.

gcse-07

On the Credential page, click create credential, then choose API Key.

gcse-08

On the popup modal, choose Browser key.

gcse-09

Name you API key and specify any URL wildcard as authorized referrers, then click create.

gcse-10

You will be prompted the API key.

gcse-11

Build the class

This section is more of a development note. Plugin users don’t have to read it.

The GoogleCustomSearch class should inherit the SearchService class that we built in the previous article so that it has all the functions that control common data logics and the UI.

There are only 3 functions to customize:

  • buildResultList(data): traverse the result array, pass url, title and digest to the common buildResult() function to generate HTML markups.
  • buildMetadata(data): generate metadata to enable pagination.
  • query(queryText, startIndex, callback): send Ajax GET request to the Google Custom Search endpoint to get search results.

In detail, we coded a class like this:

It should be as simple as initialize an instance of the GoogleCustomSearch class with your credentials:

var customSearch = new GoogleCustomSearch({
apiKey: GOOGLE_CUSTOM_SEARCH_API_KEY,
engineId: GOOGLE_CUSTOM_SEARCH_ENGINE_ID
});
  1. 1. Get Engine ID
  2. 2. Get API Key
  3. 3. Build the class
  4. 4. Enable your search