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.
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 = 'https://cse.google.com/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:
- History management is enabled
- The maximum number of displayed autocompletions is set to 5
- The Any autocompletion match mode is selected
- Refinements are displayed as links.
<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
|
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. | 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. | 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. | 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: | 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: | 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: | 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: | 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:
|
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: |
Any |
cr |
String | Restricts search results to documents originating in a particular country.
Sample usage: |
Any |
gl |
String | Boost search results whose country of origin matches the parameter value.
Sample usage: |
Any |
as_sitesearch |
String | Restrict results to pages from a specific site.
Sample usage: |
Any |
as_oq |
String | Filter search results using Logical OR.
Sample usage: |
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: |
Any |
filter |
String | Automatic filtering of search results.
Supported values: 0/1 Sample usage: |
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
classattribute must be set togcse-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
|
||||||
.go(opt_container) |
Renders all CSE tags/classes in the specified container.
Parameters
|
||||||
.getElement(gname) |
Gets the element object by gname. If not found, return null.
The returned
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 |
|
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 = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>