Custom Search

Custom Search Element Control API

You can embed Custom Search components (search boxes and search results pages) in your web pages and other web applications using HTML markup. These Custom Search elements consist of components that are rendered based on settings stored by Google's CSE server, along with any customizations you make.

All JavaScript is loaded asynchronously, which allows your webpage to continue loading while the browser fetches the Custom Search JavaScript.

Table of Contents

  1. Introduction
    1. Scope
    2. Browser compatibility
    3. Audience
  2. Custom Search elements
  3. Customizing Custom Search elements
  4. Supported attributes
  5. HTML5-valid div tags
  6. Custom Search Engine API
  7. Using the JavaScript API to render elements
    1. Script tag parameters

Introduction

This document provides a basic model for adding Custom Search elements to your web page, along with explanations of the element's configurable components and flexible JavaScript API.

Scope

This document describes how to use the functions and properties specific to the Google Custom Search Control API.

Browser compatibility

The Google Custom Search Control API currently supports Firefox 1.5+, IE6+, Safari, Opera 9+, and Chrome.

Audience

This documentation is intended for developers who wish to add Google Custom Search functionality to their pages.

Custom Search elements

You can use HTML markup to add a Custom Search element to your page. Each element consists of at least one component: a search box, a block of search results, or both. The search box accepts user input in any of the following ways:

  • A search query typed in the text input field
  • A query string embedded in a URL
  • Programmatic execution

In addition, the block of search results accepts input in the following ways:

  • A query string embedded in a URL
  • Programmatic execution

The following types of Custom Search elements are available:

Element type Component(s) Description
standard <gcse:search> A search box and search results, displayed in the same <div>.
two-column <gcse:searchbox> and <gcse:searchresults> A two-column layout with search results on one side and a search box on the other. If you plan to insert multiple elements in two-column mode in your webpage, you can use the gname attribute to pair a search box with a block of search results.
searchbox-only <gcse:searchbox-only> A standalone search box.
searchresults-only <gcse:searchresults-only> A standalone block of search results.

You can add any number of valid CSE elements to your webpage. For two-column mode, all required components (a searchbox and search results block) must be present.

Here is an example of a simple CSE element:

<!-- Put the following javascript before the closing  tag. -->
<script>
(function() {
  var cx = '123:456'; // Insert your own Custom Search engine ID here
  var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
  gcse.src = (document.location.protocol == 'https' ? 'https:' : 'http:') +
      '//www.google.com/cse/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>

<!-- Place this tag where you want both of the search box and the search results to render -->
<gcse:search></gcse:search>

Compose different layout options using Custom Search Elements

The following layout options are available on the Look and Feel tab of the Custom Search Engine control panel. Here are some general guidelines about composing layout options using Custom Search Elements. To see a demo of any of these options, click the link.

Option Component(s)
Full-width <gcse:search>
Compact <gcse:search>
Two-column <gcse:searchbox>, <gcse:searchresults>
Two-page <gcse:searchbox-only> on first page, <gcse:searchresults-only> (or other components) on second page.
Results only <gcse:searchresults-only>
Google-hosted <gcse:searchbox-only>

More information about layout options.

Customizing Custom Search elements

To customize colors, font, or link style, use the Look and feel tab of the Custom Search control panel.

You can use optional attributes to overwrite configurations created in the Custom Search control panel. This enables you to create a page-specific search experience. For example, the following code creates a search box that opens a result page (http://www.example.com?search=lady+gaga) in a new window. The value of the queryParameterName attribute, along with the user query string, is used to create the results URL.

<gcse:searchbox-only resultsUrl="http://www.example.com" newWindow="true" queryParameterName="search">

If you've used the Custom Search control panel to enable features like autocomplete or refinements, you can use attributes to customize those features. Any customizations you specify using these attributes will override settings made in the control panel. The following example creates a two-column search element with the following features:

<gcse:searchbox enableHistory="true" autoCompleteMaxCompletions="5" autoCompleteMatchType='any'>
<gcse:searchresults refinementStyle="link">

Supported attributes

Attribute Type Description Component
General
gname String (Optional) A name for the CSE element object. A name is used to retrieve an associated component by name, or to pair a searchbox component with a searchresults component. If not supplied, Custom Search will automatically generate a gname, based on the order of components on the webpage. For example, the first unnamed searchbox-only has the gname "searchbox-only0" and the second has the gname "seachbox-only1", and so on. Note that the automatically generated gname for a component in two-column layout will be two-column. The following example uses the gname storesearch to link a searchbox component with a searchresults component:
<gcse:searchbox gname="storesearch"></gcse:searchbox>
<gcse:searchresults gname="storesearch"></gcse:searchresults>

When retrieving an object, if more than one component has the same gname, Custom Search will use the last component on the page.

Any
autoSearchOnLoad Boolean Specifies whether to execute a search by the query embedded in the URL of the page that's loading. Default: true. Any
enableHistory Boolean If true, enables history management for the browser Back and Forward buttons. See a demo.

searchbox

searchbox-only

queryParameterName String The query parameter name—for example, q (default) or query. This will be embedded in the URL (for example, http://www.example.com?q=lady+gaga). Any
resultsUrl URL The URL of the results page. (Default is the Google-hosted page.) searchbox-only
newWindow Boolean Specifies whether the results page opens in a new window. Default: false. searchbox-only
Autocomplete
enableAutoComplete Boolean Only available if autocomplete has been enabled in the Custom Search control panel. true enables autocomplete. Any
autoCompleteMatchType String Specifies the autocomplete match mode. Acceptable values are: any, ordered, or prefix.

searchbox

searchbox-only

autoCompleteMaxCompletions Integer The maximum number of autocompletions to display.

searchbox

searchbox-only

autoCompleteMaxPromotions Integer The maximum number of promotions to display in autocomplete.

searchbox

searchbox-only

autoCompleteValidLanguages String Comma-separated list of languages for which autocomplete should be enabled. Supported languages.

searchbox

searchbox-only

Refinements
defaultToRefinement String Available only if refinements have been created in the Custom Search control panel. Specifies the default refinement label to display. Any
refinementStyle String Acceptable values are tab (default) and link. link is supported only if image search is disabled, or if image search is enabled but web search is disabled.

searchresults

searchresults-only

Image search
enableImageSearch Boolean Available only if image search has been enabled in the Custom Search control panel. If true, enables image search. Image results will be shown on a separate tab.

searchresults

searchresults-only

defaultToImageSearch Boolean Available only if image search has been enabled in the Custom Search control panel. If true, search results page will display image search results by default. Web results will be available on a separate tab. Any
imageSearchResultSetSize Integer, String Available only if image search has been enabled in the Custom Search control panel. Specifies the maximum size of the search results set for image search. For example, large, small, filtered_cse, 10. Any
imageSearchLayout String Available only if image search has been enabled in the Custom Search control panel. Specifies the layout of the image search results page. Acceptable values are classic, column, or popup.

searchresults

searchresults-only

image_lr String Available only if image search has been enabled in the Custom Search control panel. Restricts search results to documents written in a particular language.

Supported values

Any

image_cr String Available only if image search has been enabled in the Custom Search control panel. Restricts search results to documents originating in a particular country.

Supported values

Any

image_gl String Available only if image search has been enabled in the Custom Search control panel. Boost search results whose country of origin matches the parameter value.

Supported values

Any

image_as_sitesearch String Available only if image search has been enabled in the Custom Search control panel.

Restrict results to pages from a specific site.

Sample usage: <gcse:search image_as_sitesearch="www.abc.com"></gcse:search>

Any

image_as_oq String Available only if image search has been enabled in the Custom Search control panel.

Filter search results using Logical OR.

Sample usage: <gcse:search image_as_oq="term1 term2"></gcse:search>

Any

image_sort_by String Available only if image search has been enabled in the Custom Search control panel.

Sort results using either date or other structured content. This configuration should match the configuration set under Control Panel > Search Features > Advanced > Results Sorting.

Sample usage: <gcse:search image_sort_by="date"></gcse:search>

Any

image_filter String Available only if image search has been enabled in the Custom Search control panel.

Automatic filtering of search results.

Supported values: 0/1

Sample usage: <gcse:search image_filter="0"></gcse:search>

Any

Web search
disableWebSearch Boolean If true, disables web search. Usually used only if image search has been enabled in the Custom Search control panel.

searchresults

searchresults-only

webSearchResultSetSize Integer, String The maximum size of the results set. Applies to both image search and web search. The default depends on the layout and whether the CSE is configured to search the whole web or only specified sites. Acceptable values include:
  • An integer from 1-20
  • small: requests a small results set, typically 4 results per page.
  • large: requests a large results set, typically 8 results per page.
  • filtered_cse: requests up to 10 results per page, for a maximum of 10 pages or 100 results.
Any
webSearchSafesearch String Specifies if SafeSearch is enabled for websearch results. Accepted values are moderate, off, and active. Any
webSearchQueryAddition String Extra terms added to search query using logical OR.

Sample usage: <gcse:search webSearchQueryAddition="term1 term2"></gcse:search>

Any
lr String Restricts search results to documents written in a particular language.

Supported values

Sample usage: <gcse:search lr="lang_fr"></gcse:search>

Any
cr String Restricts search results to documents originating in a particular country.

Supported values

Sample usage: <gcse:search cr="countryFR"></gcse:search>

Any
gl String Boost search results whose country of origin matches the parameter value.

Supported values

Sample usage: <gcse:search gl="fr"></gcse:search>

Any
as_sitesearch String Restrict results to pages from a specific site.

Sample usage: <gcse:search as_sitesearch="www.abc.com"></gcse:search>

Any
as_oq String Filter search results using Logical OR.

Sample usage: <gcse:search as_oq="term1 term2"></gcse:search>

Any
sort_by String Sort results using either date or other structured content. This configuration should match the configuration set under Control Panel > Search Features > Advanced > Results Sorting.

Sample usage: <gcse:search sort_by="date"></gcse:search>

Any
filter String Automatic filtering of search results.

Supported values: 0/1

Sample usage: <gcse:search filter="0"></gcse:search>

Any
Search results
enableOrderBy Boolean Enables the sorting of results by relevance, date, or label. More information about sorting. Any
linkTarget String Sets the link target. Default: _blank.

searchresults

searchresults-only

noResultsString String Specifies the default text to display when no results match the query. The default result string can be used to display a localized string in all supported languages, while the customized one does not.

searchresults

searchresults-only

resultSetSize Integer, String The maximum size of the results set. For example, large, small, filtered_cse, 10. The default depends on the layout and whether the CSE is configured to search the whole web or only specified sites. Any
safeSearch String Specifies if SafeSearch is enabled for both web and image search. Accepted values are moderate, off, and active. Any
Ads
adchannel String If ads are enabled, the value is the id of an AdSense for Search channel. More details. Any
adclient String If ads are enabled, the value is the AdSense publisher ID. Any
adtest String Indicates that a request for ads is a test. Accepted values are on or off (default). More details. When the adtest parameter has a value of on, Google treats the request as a test and does not count the ad impressions or track the clickthrough results. When the adtest parameter has a value of on, you do not generate any revenue. Use this parameter when testing, but do not use it in production systems or you will not be paid for ads that you display. Any
Google Analytics
gaCategoryParameter String A string that defines an internal search quality, such as sale or auto. More details.

searchbox

searchbox-only

gaQueryParameter String The parameter used to define a search query for Google Analytics—for example, q or query. More details.

searchbox

searchbox-only

HTML5-valid div tags

You can use HTML5-valid div tags as long as you observe these guidelines:
  • The class attribute must be set to gcse-XXX
  • Any attributes must be prefixed with data-.

For example:

<div class="gcse-searchbox" data-resultsUrl="http://www.example.com"
data-newWindow="true" data-queryParameterName="search" >

Custom Search Element Control API (V2)

The google.search.cse.element object implements the following methods and properties:

Method Description
.render(componentConfig,opt_componentConfig) Renders a CSE element.

Parameters

Name Description
componentConfig The configuration for a Custom Search element component. Specifies the following:
  • div (string|Element): The id of the <div> or the div element in which the Custom Search element is to be rendered.
  • tag (string): The type of component(s) to be rendered. (When opt_componentConfig is supplied, the value of the tag attribute must be searchbox.) Allowed values are:
    • search: A search box and search results, displayed together
    • searchbox: A search box component of a Custom Search element.
    • searchbox-only: A standalone search box, which will be paired with a block of search results specified by opt_componentConfig in two-column layout.
    • searchresults-only: A standalone block of search results. Searches are triggered by a query parameter embedded in a URL, or by programmatic execution.
  • gname (string): (Optional) A unique name for this component. If not supplied, Custom Search will automatically generate a gname.
  • attributes (Object): Optional attributes in the form of a key:value pair. Supported attributes.
opt_componentConfig Optional. The configuration for a Custom Search element component. Specifies the following:
  • div (string): The id of the <div> or the div element in which the element is to be rendered.
  • tag (string): The type of component(s) to be rendered. When opt_componentConfig is supplied, the value of the tag attribute must be searchresults. In addition, the value of the tag attribute of componentConfig must be searchbox.
  • gname (string): (Optional) A unique name for this component. If not supplied, Custom Search will automatically generate a gname for this component. If supplied, it must match the gname in componentConfig.
  • attributes (Object): Optional attributes in the form of a key:value pair. Supported attributes.
.go(opt_container) Renders all CSE tags/classes in the specified container.

Parameters

Name Description
opt_container The container containing the CSE components to render. Specify either the ID of the container (string) or the element itself. If omitted, all Custom Search element components inside the page's body tag will be rendered.
.getElement(gname) Gets the element object by gname. If not found, return null.

The returned element object has the following attributes:

  • gname: The name of the element object. If not supplied, Custom Search will automatically generate a gname for the object. More information.
  • type: The type of element.
  • uiOptions: The final attributes used to render the element.
  • execute - function(string): Executes a programmatic query.
  • prefillQuery - function(string): Prefills the searchbox with a query string without executing the query.
  • getInputQuery - function(): Gets the current value displayed in the input box.
  • clearAllResults - function(): Clears the control by hiding everything but the search box, if any.

The following code executes the query "news" in the search element "element1":

var element = google.search.cse.element.getElement('element1);
        element.execute('news');
.getAllElements() Returns a map of all successfully created element objects, keyed by gname.

Using the JavaScript API to render elements

You can use the JavaScript API to speed up page load times by specifying that Custom Search elements are rendered only when explictly called. This can reduce page load times because you don't need to wait for the DOM to be ready. As a result, you can choose to render elements only in a subset of the document, thus reducing parsing delay. Using the JavaScript API also enables you to programmatically interact with the Custom Search element (for example, you can specify that queries submitted via a custom search form are executed in a searchresults-only element). See a demo.

Script tag parameters

You can pass script tag parameters by passing them in window.__gcse object, placed before /cse.js script.

Parameter Description
parseTags
  • explicit: Components are rendered only with explicit calls to google.search.cse.element.render() or google.search.cse.element.go(). Used together with the callback parameter.
  • onload (default): All CSE components inside the page's body tag are automatically rendered after the page loads.
callback Specifies the callback function to call when the initialization process is completed.

The following code demonstrates how to render a search box, together with search results, in a div, using the explicit parsetag and function callback:

<div id="test"></div>

<script>
var myCallback = function() {
  if (document.readyState == 'complete') {
    // Document is ready when CSE element is initialized.
    // Render an element with both search box and search results in div with id 'test'.
    google.search.cse.element.render(
        {
          div: "test",
          tag: 'search'
         });
  } else {
    // Document is not ready yet, when CSE element is initialized.
    google.setOnLoadCallback(function() {
       // Render an element with both search box and search results in div with id 'test'.
        google.search.cse.element.render(
            {
              div: "test",
              tag: 'search'
            });
    }, true);
  }
};

// Insert it before the CSE code snippet so that cse.js can take the script
// parameters, like parsetags, callbacks.
window.__gcse = {
  parsetags: 'explicit',
  callback: myCallback
};

(function() {
  var cx = '123:456'; // Insert your own Custom Search engine ID here
  var gcse = document.createElement('script'); gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = (document.location.protocol == 'https' ? 'https:' : 'http:') +
      '//www.google.com/cse/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.