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.

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 list of browsers supported by Custom Search can be found here.

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 <div class="gcse-search"> A search box and search results, displayed in the same <div>.
two-column <div class="gcse-searchbox"> and <div class="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 <div class="gcse-searchbox-only"> A standalone search box.
searchresults-only <div class="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 </head> tag
and replace 123:456 with your own Custom Search engine ID. -->
<script async src="https://cse.google.com/cse.js?cx=123:456"></script>

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

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 <div class="gcse-search">
Compact <div class="gcse-search">
Two-column <div class="gcse-searchbox">, <div class="gcse-searchresults">
Two-page <div class="gcse-searchbox-only"> on first page, <div class="gcse-searchresults-only"> (or other components) on second page.
Results only <div class="gcse-searchresults-only">
Google-hosted <div class="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.

Note that the queryParameterName attribute is prefixed with data-. This prefix is required for all attributes.

<div class="gcse-searchbox-only" data-resultsUrl="http://www.example.com" data-newWindow="true" data-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:

<div class="gcse-searchbox" data-enableHistory="true" data-autoCompleteMaxCompletions="5" data-autoCompleteMatchType='any'>
<div class="gcse-searchresults" data-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:
<div class="gcse-searchbox" data-gname="storesearch"></div>
<div class="gcse-searchresults" data-gname="storesearch"></div>

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
personalizedAds Boolean

Specifies whether users have consented to allowing the publisher to share personal information with Google for the purpose of personalized advertising.

true Returns query targeted ads and some ads that may be targeted with the user's Google cookies. If the user is located in the European Union, the user must first consent to allowing your site to share personal information with Google for the purpose of personalized advertising.

false Returns only query targeted ads. This will not return any ads that are targeted with the user's Google cookies. If a user has declined consent for allowing your site to share personal information with Google for the purpose of personalized advertising, you must set this value to false.

Default: true

Sample usage: <div class="gcse-search" data-personalizedAds="false"></div>

Any
mobileLayout String

Specifies whether the mobile layout styles should be used for mobile devices.

enabled Uses the mobile layout for mobile devices only.

disabled Does not use the mobile layout for any devices.

forced Uses the mobile layout for all devices.

Default: enabled

Sample usage: <div class="gcse-search" data-mobileLayout="disabled"></div>

Any
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.Note: This attribute is not supported for Google Hosted layout. 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
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

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
image_as_filetype String Available only if image search has been enabled in the Custom Search control panel.

Restricts results to files of a specified extension.

Supported extensions are jpg, gif, png, bmp, svg, webp, ico, raw.

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 if you want search results that include either "term1" or "term2":<div class="gcse-search" data-image_as_oq="term1 term2"></div>

Any

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

Filters based on licensing.

Supported values are cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived, and combinations of these.

See typical combinations.

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: <div class="gcse-search" data-image_as_sitesearch="www.abc.com"></div>

Any

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

Restricts search to black and white (mono), grayscale, or color images. Supported values are mono, gray, color.

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_dominantcolor String Available only if image search has been enabled in the Custom Search control panel.

Restricts search to images of a specific dominant color. Supported values are red, orange, yellow, green, teal, blue, purple, pink, white, gray, black, brown.

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: <div class="gcse-search" data-image_filter="0"></div>

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_size String Available only if image search has been enabled in the Custom Search control panel.

Returns images of a specified size, where size can be one of: icon, small, medium, large, xlarge, xxlarge, or huge.

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.

To sort by relevance use an empty string (image_sort_by="").

Sample usage: <div class="gcse-search" data-image_sort_by="date"></div>

Any

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

Restricts search to images of a specific type. Supported values are clipart (Clip art), face (Faces of people), lineart (Line drawings), stock (Stock photos), photo (Photographs), and animated (Animated GIFs).

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

webSearchQueryAddition String Extra terms added to search query using logical OR.

Sample usage: <div class="gcse-search" data-webSearchQueryAddition="term1 term2"></div>

Any
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
as_filetype String Restricts results to files of a specified extension. A list of file types indexable by Google can be found in Search Console Help Center.

Any

as_oq String Filter search results using Logical OR.

Sample usage if you want search results that include either "term1" or "term2":<div class="gcse-search" data-as_oq="term1 term2"></div>

Any
as_rights String Filters based on licensing.

Supported values are cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived, and combinations of these.

See https://wiki.creativecommons.org/wiki/CC_Search_integration for typicall combinations.

Any

as_sitesearch String Restrict results to pages from a specific site.

Sample usage: <div class="gcse-search" data-as_sitesearch="www.abc.com"></div>

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

Supported values

Sample usage: <div class="gcse-search" data-cr="countryFR"></div>

Any
filter String Automatic filtering of search results.

Supported values: 0/1

Sample usage: <div class="gcse-search" data-filter="0"></div>

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

This will only work in conjunction with the CSE language value setting.

Supported values

Sample usage: <div class="gcse-search" data-gl="fr"></div>

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

Supported values

Sample usage: <div class="gcse-search" data-lr="lang_fr"></div>

Any
sort_by String Sort results using either date or other structured content. The attribute value must be one of the options provided in Control Panel > Search Features > Advanced > Results Sorting.

To sort by relevance use an empty string (sort_by="").

Sample usage: <div class="gcse-search" data-sort_by="date"></div>

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

Callbacks

Callback Sequence Diagram
sequence diagram of callbacks from search element JavaScript

Callbacks support detailed control of the search-element initialization and search processes. They are registered with the search element JavaScript through the global __gcse object. Register Callbacks illustrates registration of all the supported callbacks.

Register Callbacks

  window.__gcse = {
    parsetags: 'explicit', // Defaults to 'onload'
    initializationCallback: myInitializationCallback,
    searchCallbacks: {
      image: {
        starting: myImageSearchStartingCallback,
        ready: myImageResultsReadyCallback,
        rendered: myImageResultsRenderedCallback,
      },
      web: {
        starting: myWebSearchStartingCallback,
        ready: myWebResultsReadyCallback,
        rendered: myWebResultsRenderedCallback,
      },
    },
  };
  

The Initialization Callback

The initialization callback is invoked before the search element JavaScript renders search elements in the DOM. If parsetags is set to explicit in __gcse, the search element JavaScript leaves rendering search elements to the initialization callback (as shown in Register Callbacks). This might be used to select elements to render, or to defer rendering elements until they are needed. It can also override the attributes of the elements; for instance, it can turn a searchbox that is configured through the CSE Control Panel or HTML attributes to default to web search into an image search box, or specify that queries submitted via a custom search form are executed in a searchresults-only element. See a demo.

The role of the initialization callback is controlled by the value of the parsetags property of __gcse.

  • If its value is onload, the search element JavaScript renders all search elements on the page automatically. The initialization callback is still invoked, but it is not responsible for rendering the search elements.
  • If its value is explicit, the search element JavaScript does not render search elements. The callback may render them selectively using the render() function, or render all search elements with the go() function

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

Initialization Callback Example

We need to include a <div> with an id value where we'd like the search element code:

    <div id="test"></div>
Add this JavaScript after the <div>. Note that it references test, the id we used to identify the <div>
const myInitCallback = 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 the global properties like parsetags and callback
// are available when cse.js runs.
window.__gcse = {
  parsetags: 'explicit',
  initializationCallback: myInitCallback
};

Include this HTML to start loading the CSE element. Replace the cx value in the src clause with your own cx.

<script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>

Search Callbacks

The search element JavaScript supports six callbacks that operate in the search control flow. The search callbacks come in pairs, a web-search callback and matching image-search callback:

  • Search Starting
    • For image search
    • For web search
  • Results ready
    • For image search
    • For web search
  • Results rendered
    • For image search
    • For web search

Like the initialization callback, the search callbacks are configured using entries in the __gcse object. This happens as the search element JavaScript starts. Modifications to __gcse after startup are ignored.

Each of these callbacks is passed the gName for the search element as an argument. The gname is useful when a page contains more than one search. Give a search element a gname values using the data-gname attribute:

<div class="gcse-searchbox" data-gname="storesearch"></div>

If the HTML doesn’t identify the gname, the search element JavaScript generates a value that will remain consistent until the HTML is modified.

Image/Web Search-Starting Callback

The search starting callbacks are invoked immediately before the search element JavaScript requests search results from its server. An example use-case would be using the local time of day to control changes to the query.

searchStartingCallback(gname, query)
gname
search element's identifying string
query
value entered by the user (possibly modified by search element JavaScript.)

The callback returns the value that should be used as the query for this search. If it returns an empty string, the return value is ignored and the caller uses the unmodified query.

Alternatively, you can put the callback function in the __gcse object or dynamically add the callback to the object with JavaScript:

window.__gcse['searchCallbacks']['web']['starting'] = function(gname, query) {...};
Example Search Starting Callback

The example search starting callback in Example Search Starting Callback adds either morning or afternoon to the query depending on the time of day.

Search Starting Callback Example
    const myWebSearchStartingCallback = (gname, query) => {
      const hour = new Date().getHours();
      return query + (hour < 12 ? ' morning' : ' afternoon');
    };
    window.myImageSearchStartingCallbackName = myWebSearchStartingCallback;

Install this callback in window.__gcse:

  window.__gcse || (window.__gcse = {});
    window.__gcse.searchCallbacks = {
      image: {
        starting: 'myImageSearchStartingCallbackName',
      },
      web: {
        starting: myWebSearchStartingCallback,
      },
    };
  
  <script
  async src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

Image/Web Search Results-Ready Callback

These callbacks are invoked immediately before the search element JavaScript renders promotions and results. An example use case would a callback that renders promotions and results in a style that cannot be specified with normal CSE-customization.

resultsReadyCallback(gname, query, promos, results, div)
gname
search element's identifying string
query
query that produced these results
promos
an array of promotion objects, which correspond to matched promotions for the user’s query. See the promotion object definition.
results
an array of result objects. See the result object definition.
div
an HTML div positioned in the DOM where the search element would ordinarily place promotions and search results. Normally, the search element JavaScript would handle populating this div, but this callback may choose to stop the automatic rendering of results and use this div to render results itself.

If this callback returns a true value, the search element JavaScript skips to its page-footer work.

Example Results Ready Callback

The example resultsReady callback in Example Results Ready Callback overrides the default presentation of promotions and results with a very simple replacement.

Results Ready Callback Example
    const myResultsReadyCallback = function(name, q, promos, results, resultsDiv) {
      const makePromoElt = (promo) => {
        const anchor = document.createElement('a');
        anchor.href = promo['url'];
        anchor.target = '_blank';
        anchor.classList.add('gs-title');
        const span = document.createElement('span');
        span.innerHTML = 'Promo: ' + promo['title'];
        anchor.appendChild(span);
        return anchor;
      };
      const makeResultParts = (result) => {
        const anchor = document.createElement('a');
        anchor.href = result['url'];
        anchor.target = '_blank';
        anchor.classList.add('gs_title');
        anchor.appendChild(document.createTextNode(result['visibleUrl']));
        const span = document.createElement('span');
        span.innerHTML = ' ' + result['title'];
        return [anchor, span];
      };

      const table = document.createElement('table');
      if (promos) {
        for (const promo of promos) {
          const row = table.insertRow(-1);
          const cell = row.insertCell(-1);
          cell.appendChild(makePromoElt(promo));
        }
        resultsDiv.appendChild(table);
        resultsDiv.appendChild(document.createElement('br'));
      }
      if (results) {
        const table = document.createElement('table');
        for (const result of results) {
          const row = table.insertRow(-1);
          const cell = row.insertCell(-1);
          const [anchor, span] = makeResultParts(result);
          cell.appendChild(anchor);
          const cell2 = row.insertCell(-1);
          cell2.appendChild(span);
        }
        resultsDiv.appendChild(table);
      }
      return true;
    };

Install this callback in window.__gcse:

  window.__gcse || (window.__gcse = {});
    window.__gcse.searchCallbacks = {
      web: {
        ready: myResultsReadyCallback,
      },
    };
  <script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

As with the search starting callback, the above is one of many ways to put the callback in the __gcse object.

Image/Web Search Results-Rendered Callback

These callbacks are invoked immediately before the search element JavaScript renders the page footer. Example use cases would include a callback that adds result content that the search element does not display such as a save this checkbox or information that is not automatically rendered, or a callback that adds for more information buttons.

If a results rendered callback needs information that was in the promos and results arguments of the results ready callback, it can pass that between them, like this:

callback(gname, query, promoElts, resultElts);
gname
search element's identifying string
query
search string.
promoElts
an array of the DOM elements containing promotions.
resultElts
an array of the DOM elements containing results.

There is no return value.

Example Results Rendered Callback

The example resultsRendered callback in Example Results Rendered Callback adds a dummy Keep checkbox to each promotion and result.

Results Rendered Callback Example
myWebResultsRenderedCallback = function(name, q, promos, results) {
    for (const div of promos.concat(results)) {
      const innerDiv = document.createElement('div');
      innerDiv.appendChild(document.createTextNode('Keep: '));
      const checkBox = document.createElement('input');
      checkBox.type = 'checkbox';
      checkBox.name = 'save';
      innerDiv.appendChild(checkBox);
      div.insertAdjacentElement('afterbegin', innerDiv);
    }
  };

Install this callback in window.__gcse:

window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  web: {
    rendered: 'myWebResultsRenderedCallback',
  },
};
  <script async
    src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

If the results rendered callback needs information that was passed to the results ready callback it can pass that data between the callbacks. The following example shows one of many ways to pass a rating value from richSnippet from the results ready callback to the results rendered callback.

Example of Results Ready Callback Cooperating with Results Rendered Callback
const makeTwoPartCallback = () => {
  let saveForRenderCallback;
  const readyCallback = (name, q, promos, results, resultsDiv) =>
  {
    saveForRenderCallback = [];
    for (const result of results) {
      const {
        richSnippet: {
          answer = []
        } = {},
      } = result;
      const firstAnswer = answer[0];
      if (firstAnswer) {
        const upVotes = firstAnswer['upvotecount'];
        if (upVotes) {
          saveForRenderCallback.push(
            {upvotes: parseInt(upVotes, 10)}
          );
          continue;
        }
      }
      saveForRenderCallback.push({});
    }
  };
  const renderedCallback = (name, q, promos, results) => {
    for (let i = 0; i < results.length; ++i) {
      const div = results[i];
      const votes = saveForRenderCallback[i]['upvotes'];
      if (votes) {
        const innerDiv = document.createElement('div');
        innerDiv.innerHTML = '<b>Upvotes: ' + votes + '</b>';
         div.insertAdjacentElement('afterbegin', innerDiv);
      }
    }
  };
  return {readyCallback, renderedCallback};
};
Install this callback using code like this while setting up __gse:
const {
  readyCallback: webResultsReadyCallback,
  renderedCallback: webResultsRenderedCallback,
} = makeTwoPartCallback();
window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  web: {
    ready: webResultsReadyCallback,
    rendered: webResultsRenderedCallback,
  },
};
  <script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:kdroeu4mwju"></script>
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

Promotion and Result Properties

Using JSDoc notation, these are the properties of promotion and result objects. Here, we list all the properties that might be present. The presence of many of the properties depend on the details of the promotion or search result.

Promotion Properties
{
  content: string,
  image: {
    height: number,
    url: string,
    width: number,
  },
  title: string,
  url: string,
  visibleUrl: string,
}
Result Object Properties
{
  content: string,
  contentNoFormatting: string,
  contextUrl: string, // For image search results only
  fileFormat: string,
  image: { // For image search reseults only
    height: number,
    url: string,
    width: number,
  },
  perResultLabels: !Array<{
    anchor: string,
    label: string,
    labelWithOp: string,
  }>,
  richSnippet: !Array<!Object>, // For web search results only
  thumbnailImage: {
    height: number,
    url: string,
    width: number,
  },
  title: string,
  titleNoFormatting: string,
  url: string,
  visibleUrl: string,
}

richSnippet in results has the loose type of an array of objects. The values of entries in this array are controlled by the structured data found on the web page for each search result. For instance, a review web site might include structured data that adds this array entry to richSnippet:

'review': {
  'ratingstars': '3.0',
  'ratingcount': '1024',
},

Custom Search Element Control API (V2)

The google.search.cse.element object publishes the following static functions:

Function 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. Second component configuration argument. Used in TWO_COLUMN mode to provide the searchresults 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.