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.
Go to next. Enter your website domain. Then click the create button.
On the congratulations screen, click Control Panel.
On the control panel, click Search Engine ID, note down the ID in the popup modal.
Get API Key
Go to Google API Console. You may need to register first. Click ENABLE API.
Search for "custom search", click on the first result.
On the Custom Search API page, click on Credential in the left side bar.
On the Credential page, click create credential, then choose API Key.
On the popup modal, choose Browser key.
Name you API key and specify any URL wildcard as authorized referrers, then click create.
You will be prompted the API key.
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 commonbuildResult()
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:
https://gist.github.com/artchen/212e08ff3ae2290c7b6c0dcfb32a407f.js
Enable your search
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
});