Add Google Search To Your Website

August 15, 2017
Embed Google Custom Search.

Visit Google Custom Search, click Add to create a Custom Search Engine.

For Sites to search, use www.mydomain.com/* to include entire site, or www.mydomain.com/tutorials/* to include certain path only; multiple entry is supported. Learn more about URL patterns.

Create Google Custom Search

If you pages implement Schema.org, you can use it to restrict pages to certain types only. Click on Advance Options and put in the Schema.org type to allow for listing and searching.

Note: applying Schema.org types restriction show no result for my case, not sure it’s a bug or Google have yet to crawl the markup.

Google Custom Search Schema.org Restriction

Click Save. Upon success, click on Get Code to integrate search into your website (probably on a page which handle search, e.g. https://www.mydomain.com/search).

Google Custom Search Success

<script>
  (function() {
    var cx = 'custom-search-engine-id';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
  })();
</script>
<gcse:search></gcse:search>

The default search implementation is the search result will be displayed in a popup overlay. If you want the search result to be embed within the page without a popup, click on Control Panel > Look and feel, select Full width then click Save (no changes of code is necessary as the settings are saved on the server side).

Google Custom Look and Feel

To have a search bar at the top of the page, just implement a HTML form which send q query parameter to the search page. URL request like https://www.mydomain.com/search?q=android will trigger the search.

<form action="/search" role="search">
  <fieldset>
    <input type="search" placeholder="Search" type="text" name="q" >
  </fieldset>
</form>

Final result.

Note: Ads are served in the search result, though you can monetize it through integration with AdSense (click on Make money at control panel).

Google Custom Search Result

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.