Custom Search

JavaScript API Reference

The Custom Search Element is a control that provides the user interface (UI) for a Google Custom Search Engine (CSE). Using the Custom Search Element JavaScript API, you can configure the Google Custom Search UI, search parameters, and result rendering. The Custom Search Element API consists of the following objects:

  • The CustomSearchControl object implements the Custom Search Element, which comprises the Custom Search engine and UI. Calling the constructor initializes the Custom Search service and UI; other methods allow you to control search queries, results, and UI.
  • The ImageSearch object controls image search queries and results. It inherits methods and properties from the Search object .
  • The WebSearch object controls web search queries and results. It inherits methods and properties from the Search object .
  • The DrawOptions object controls how the UI and results are displayed, as well as whether the search control uses autocompletion.
  • The Custom Search Engine Data Renderer object allows you to write HTML to include rich snippets and other custom data attributes.

Contents

  1. Custom Search Element
    1. CustomSearchControl Object
    2. Search Object
    3. ImageSearch Object
    4. WebSearch Object
    5. DrawOptions Object
    6. Data Renderer Object
  2. Creating your own search form
  3. Troubleshooting

CustomSearchControl Object

The google.search.CustomSearchControl object provides a ready-made user interface (UI) for Google Custom Search results, and allows you to execute searches programmatically from Custom Search. This object implements the following methods and properties:

CustomSearchControl Constructor

Syntax

    google.search.CustomSearchControl.CustomSearch
          Control(cseId, opt_options);

Description

This constructor creates an instance of the CustomSearchControl object, which represents a Custom Search Element. Calling this constructor initializes the Custom Search service and UI.

Parameters

This constructor takes the following parameters:

cseId

Specifies the CSE ID cx parameter for a Stored Custom Search Engine, or a cref URL for a Linked Custom Search Engine.

For a Stored Custom Search Engine, for example, the CSE ID can be a string, such as '012345678901234567890:abcdefghijk' or a key- value pair, such as {'cseId': '012345678901234567890:abcdefghijk'} .

On the other hand, if the specification for a Linked Custom Search Engine is located at www.examplepetstore.com, the cref URL would be specified as follows:

        {'crefUrl' : 'http://www.examplepetstore.com/cref_cse.xml'}
        

Linked Custom Search Engines are free, ad-supported search engines.

See Linked Custom Search Engines for a detailed explanation of CSE IDs and cref URLs.

opt_options

An optional parameter that specifies default search settings as key- value pairs. It controls settings such as the SafeSearch level, search restrictions, AdSense channel, and publisher, web search options, and image search options. Web search and image search settings are passed to the respective searchers. The following keys are supported:


  • autoCompleteOptions specifies how autocompletions should be triggered and displayed in search results. The following parameters are supported:
    • matchType. Specifies the autocompletion type. Accepted values are any, prefix, or ordered.
    • maxCompletions (number): The maximum completions (excluding promotions) to display in the autocompletion table.
    • maxPromotions (number): The maximum number of promotions to display in the autocompletion table. The valid range is from 0 to 3. If not set, the default is 3.
    • validLanguages (string): Optional. A comma-delimited list of language codes (for example, en,fr,ja). If specified, autocompletions will only appear for listed languages. When this option is not specified, autocompletions will be displayed for all languages by default.

  • google.search.Search.RESTRICT_EXTENDED_ARGS specifies additional query parameters for filtering and sorting. Define the query parameters in a separate object, then pass the object to the opt_options parameter. The most useful query parameters are typically:
    • lr restricts the search by language. See a full list of language codes.
    • cr restricts the search by country. See a full list of country collection codes.
    • gl boosts results by locale. See a full list of locale codes.
    • filter enables or disables automatic result filtering
    • sort sorts results
    • as_sitesearch limits search results to pages within the specified site.
    • as_oq provides additional search terms where each term is joined by an OR instead of AND

    • The following is an example of how to use lr and sort to restrict the language to Italian and sort results by date:
      options[google.search.Search.RESTRICT_EXTENDED_ARGS] = {
        'lr': 'lang_it',
        'sort': 'date'
      };
      var customSearchControl = new google.search.CustomSearchControl(id, options);
      

      The following is an example of how to use as_sitesearch:
      var options = {}
      options[google.search.Search.RESTRICT_EXTENDED_ARGS] =
        {'as_sitesearch' : 'examplepetstore.com/dogs/'};
      var customSearchControl = new google.search.CustomSearchControl(
       '012345678901234567890:abcdefghijk', options);
      

      Web search query parameters are described in the XML API reference. Sort parameters are described in Filtering and sorting search results. The extended query parameters that you specify persist for subsequent searches, and you need to call ImageSearch.setRestriction() or WebSearch.setRestriction() again to change them.

  • google.search.Search.RESTRICT_SAFESEARCH sets the SafeSearch level. This setting corresponds to Search settings in Google Web Search. Supported values are:
    • google.search.Search.SAFESEARCH_OFF disables SafeSearch filtering.
    • google.search.Search.SAFESEARCH_MODERATE excludes sexually explicit video and images from search result pages, but does not filter results that might link to explicit content. This is the default SafeSearch setting for Google searches.
    • google.search.Search.SAFESEARCH_STRICT filters out sexually explicit video and images from search result pages, as well as results that might link to explicit content.

  • adchannel is the AdSense channel tracking code. Publishers can create custom channels to compare and differentiate ad placements in their revenue performance statistics (for example, different custom channels mught be called "forums channel," "home page channel," and "search page channel"). For more information, see Custom channels overview.

  • adclient is the AdSense publisher id. It is similar to the publisher parameter of .enableAds(). You don't need to set this if you have linked your AdSense publisher account in the Make money tab of the Custom Search Control Panel to that particular Custom Search Element. What you set using adclient or .enableAds() is ignored in favor of what you specify in the Control Panel.

  • disableWebSearch is a Boolean value. If true, web search is disabled. If false, web search is enabled. This setting is ignored when image search is not enabled.

  • webSearchOptions sets options that apply only to web search:
    • google.search.Search.RESTRICT_EXTENDED_ARGS specifies additional query parameters for filtering and sorting, as described in opt_options above.
    • google.search.Search.RESTRICT_SAFESEARCH sets the SafeSearch level, as described in opt_options above.
    • google.search.WebSearch.resultSetSize is the web search result set size. See WebSearch.setResultSetSize().

  • enableImageSearch enables image search.

  • imageSearchOptions sets options that apply only to image search:
    • google.search.Search.RESTRICT_SAFESEARCH sets the SafeSearch level, as described in opt_options above.
    • resultSetSize is the image search result set size. See ImageSearch.setResultSetSize().
    • layout specifies the layout of the image search results. Supported values are:
      • google.search.ImageSearch.LAYOUT_CLASSIC displays image results in classic layout.
      • google.search.ImageSearch.LAYOUT_POPUP displays image results in pop-up layout. Thumbnails are displayed as pop-up images on mouseover. This layout tries to scale pop-up images to their full width, but limits their height.
      • google.search.ImageSearch.LAYOUT_COLUMN displays image results in column layout. This layout tries to scale the preview images to their full height, but limits their width.

  • defaultToImageSearch sets image searcher as the default search.

  • defaultToRefinement default refinement in default searcher with which to start the query.

You can also call the Custom Search Element constructor with no values, in which case it automatically restricts searches to the current site. For example, if you call the constructor from http://www.examplepetstore.com, Custom Search automatically restricts results to content in the examplepetstore.com domain.

Once you call the Custom Search Element constructor, bind it to a div as follows:

// Create a Custom Search Element
var customSearchControl = new google.search.CustomSearchControl();

// Draw the control in example-div
customSearchControl.draw('example-div');

Return value

  • A google.search.CustomSearchControl object.

Back to top

CustomSearchControl Methods

Method Return Type Description
.cancelSearch() None

Calling this method tells the search control to ignore any incoming search result responses. It can be used when processing an uncompleted search is no longer needed.

Return value

  • This method does not return a value.
.clearAllResults() None

Clears the search results from the Custom Search Element.

Return value

  • This method does not return a value.
.draw(
  element,
  opt_drawOptions)
None

Displays the search form and search results. Calling this method is the final step in activating a Custom Search Element object, and it produces the UI and search result containers.

Parameters

Name Description
element Is the node in which the CustomSearchControl object is rendered (a string ID or the HTML element itself). This supplies an HTML element (typically a div element) in which the Custom Search Element can draw the search form and results. The element operates best when you provide it with at least 300px of width, and it scales reasonably well down to 250px.
opt_drawOptions Is a google.search.DrawOptions object that specifies the drawing mode of the searcher. To override the default drawing options, call methods on the google.search.DrawOptions object and pass it to this parameter.

For example, to use .draw to create a custom input box, call the method as follows:

google.load('search', '1');

function onLoad() {
  // Create a Custom Search Element that uses a
  // Custom Search Engine restricted to code.google.com.
  // Change the customSearchId string to the CSE ID of
  // your own Custom Search engine.
  var customSearchControl =
    new google.search.CustomSearchControl(
      '012345678901234567890:abcdefghijk');
  customSearchControl.enableAds(/* your publisher ID */);

  // Set drawing options to set the root element for the
  // search form (where you have defined a div such as
  // <div id="search-form">)
  var drawOptions = new google.search.DrawOptions();
  drawOptions.setSearchFormRoot('search-form');

  // Draw the search results in the results div
  customSearchControl.draw('results', drawOptions);
}

google.setOnLoadCallback(onLoad);

Return value

  • This method does not return a value.
.enableAds(publisher) None

Associates an AdSense publisher ID with your Custom Search Element, where pubId supplies the publisher ID. Supplying a publisher ID allows you to share in the revenue from ads shown with the results.

Note: If you supplied a Custom Search publisher ID in the adclient parameter of the constructor, this method has no effect. Instead, enter your AdSense publisher ID in the Custom Search control panel. Settings made with .enableAds() are ignored in favor of settings made in the Custom Search Control Panel.

Parameters

Name Description
publisher The publisher ID.

Return value

  • This method does not return a value.
.execute(
  opt_query,
  opt_page,
  opt_extraParams)
None

Executes a search, where opt_query supplies an optional search expression. If you do not supply opt_query, the current value of the input form becomes the search expression.

Parameters

Name Description
opt_query Specifies the query string.
opt_page Specifies the results page number to request, as an integer starting at 1.
opt_extraParams Specifies additional arguments to append to the URL. It is a one-time modification used only in this request.

This method allows applications to automate portions of the search control. For example, you can automatically initiate a search whenever the user hovers over a word or phrase or makes some other application- specific gesture.

This method also displays the current set of search results and clears results currently stored in the searcher.

Return value

  • This method does not return a value.
.getImageSearcher() google.search.
ImageSearch

Retrieves the current image searcher object.

Return value

  • An image searcher object.
.getInputQuery()

String

Retrieves the current contents of the input box.

Return value

  • For Web searches, this method returns the current content of the input box as a string.
.getTrackingCategory() String

Retrieves the search refinement, which is used as the category for Google Analytics tracking.

Return value

  • For Web searches, this method returns the refinement name as a string. For Image searches, this method returns a string composed of the searcher name and the refinement name; for example, if the search refinement is "Products," then the returned string is 'image:products'.
.getWebSearcher() google.search.
WebSearch

Retrieves the current web searcher object.

Return value

  • A web searcher object.
.prefillQuery()

String

Sets a specified string as the contents of the input box.

Return value

  • This method does not return a value.
.setAutoCompletionId(id) None

DEPRECATED. Instead, use matchType to specify the type of pattern matching to be used in the autocompletion request.

Parameters

Name Description
id

Specifies the type (match mode) of autocompletion to be used:

  • qptype:1 specifies that Custom Search should display autocompletions regardless of the order of the words in the triggering query. For example, sitemap submit will trigger both how to submit sitemap and submit video sitemap. This is the same as selecting a match mode of "Any."
  • qptype:3 specifies that Custom Search should display autocompletions when the trigger terms in the user query match both the words in the autocompletion and the order in which those words appear. This is the same as selecting a match mode of "Ordered."

Pass id as a string that concatenates the cseId (cx parameter) value , '+' , and one of the autocompletion types above, for example:

012345678901234567890:abcdefghijk+qptype:1

Return value

  • This method does not return a value.
.setLinkTarget(linkTarget) None

Sets the link target for links embedded in search results (that is, the value of target= in the <a> tag.

Parameters

Name Description
linkTarget Supplies the target frame in which to open links; the following values are supported:
  • google.search.Search.LINK_TARGET_BLANK opens links in a new window (for example, <a href=... target=_blank ...>). This is the default.
  • google.search.Search.LINK_TARGET_SELF opens links in the same window and frame (for example, <a href=... target=_self ...>).
  • google.search.Search.LINK_TARGET_TOP opens links in the topmost frame (for example, <a href=... target=_top ...>).
  • google.search.Search.LINK_TARGET_PARENT either opens links in the topmost frame, or replaces the current frame (for example, <A href=... target=_parent ...>).
  • anything-else specifies that links open in the specified frame or window (for example, <a href=... target=anything-else ...>).

Return value

  • This method does not return a value.
.setNoResultsString(str) None

Specifies the default text to display when no results match the query. The system stores the default result string in the google.search.SearchControl.NO_RESULTS_DEFAULT_STRING property, which you can use to display a localized string in all supported languages.

Parameters

Name Description
str A string that specifies the text to display when no results match the query.

Return value

  • This method does not return a value.
.setOnKeepCallback(
  object,
  method,
  opt_keepLabel)
None

Instructs the Custom Search Element to notify the caller when a user selects a search result for copy. If you do not call this method, users are not offered the option to copy a result. If you call this method, a link appears beneath each search result. Clicking the link calls the specified method on the specified object, passing in a google.search.Result object associated with the search result.

This method allows the caller to specify a built-in, system-defined text label value which invites the user to copy a result, or to specify a label more meaningful to the calling application. When using the system- defined labels, the value is automatically translated into the primary language used in the control.

Parameters

Name Description
object Specifies an application-level object that defines the context in which to call the specified method.
method Specifies the method to call. For example, if you call this method as .setOnKeepCallback(foo, MyObject.prototype. myKeephandler) , clicking on the keep label calls foo.myKeephandler().
opt_keepLabel Specifies the optional text label displayed under each search result. Clicking this label triggers a callback into the specified object/method. Supported values are:
  • google.search.SearchControl.KEEP_LABEL_COPY sets a label value of copy. This is the default.
  • google.search.SearchControl.KEEP_LABEL_SAVE sets a label value of save.
  • google.search.SearchControl.KEEP_LABEL_KEEP sets a label value of keep.
  • google.search.SearchControl.KEEP_LABEL_INCLUDE sets a label value of include.
  • google.search.SearchControl.KEEP_LABEL_BLANK supplies a copy graphic (selectable through CSS) without the label value.
  • You can also enter a value for the label, but in this case the caller is responsible for localization.

Return value

  • This method does not return a value.
.setRefinementStyle(style) None

Sets the refinement style as tabs or links.

Parameters

Name Description
style Specifies how search refinements appear in the UI. The following values are supported:
  • google.search.SearchControl.REFINEMENT_AS_TAB specifies that search refinements appear as tabs.
  • google.search.SearchControl.REFINEMENT_AS_LINK specifies that search refinements appear as links.

Return value

  • This method does not return a value.
.setSearchCompleteCallback(
  object,
  method)
None

Specifies a callback method to call upon completion of the search, and a context object for that method. In the Custom Search model, the method calls are asynchronous. Therefore, you cannot block on the return and use the results. Rather, you have to use a callback, which executes a method when the search returns the results.

Parameters

Name Description
object Specifies an application-level object that defines the context in which to call the specified method.
method Specifies the callback method.

Return value

  • This method does not return a value.
.setSearchStartingCallback(
  object,
  method)
None

Specifies a callback method to call upon initiation of the search. The Custom Search Element notifies the caller before the search begins.

Parameters

Name Description
object Specifies an application-level object that defines the context in which to call the specified method.
method Specifies the callback method.

Return value

  • This method does not return a value.
.setUserDefinedLabel(label) None

Specifies labels for the web and image tabs of the Custom Search Element.

Parameters

Name Description
label is the tab label, which you can specify as a string or an object:
  • When you provide a string, and if web search is enabled on the Custom Search Element, only web search takes this string as its label (and image search uses "Image" as its label). If only image search is enabled on the Custom Search Element, image search takes this string as its label.
  • When you provide an object, the searcher labels are set using the key-value pairs in that object, where the key specifies the searcher tab with 'web' or 'image', and the value is a user-defined string.

For example, you could make the following call to change the default labels of the web and image tabs:

customSearchControl.setUserDefinedLabel({'web':'Search entire web',
  'image':'Search images only'});

Return value

  • This method does not return a value.
.startHistoryManagement(
  opt_initializationCallback)
Boolean

See a demo of the History Management feature.

Enables storage of search control states in the web browser history. History management uses the web browser URL hash to store the search control state, including the control's currently selected tab, the last executed search, and the results page number.

If any search control state is present in the URL when you call this method, the search control updates to reflect that state. Otherwise, it first calls the initialization callback argument (if you specified one), then replaces the current browser history entry with the state of the control after the callback finishes.

If your website already uses the URL hash for tracking, you should update your code to ignore the search control state.

For example, you could have the following code, which initializes the search control with history:

customSearchControl.draw('cse');
  var historyStarted = customSearchControl.startHistoryManagement(
    function() {
      // Only search for defaultQuery if there's no existing history state
      //  in the URL
      customSearchControl.execute(defaultQuery);
    });
  if (historyStarted) {
    // History is enabled so results can be opened in the same window
    //  safely
    customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
  }

Parameters

Name Description
opt_initializationCallback A callback method that performs initialization when no initial state is already present in the hash. The search control can also call it if history management is not enabled in the web browser. The callback method takes the current CustomSearchControl object as a parameter.

Return value

  • A Boolean value. true indicates that the browser is supported. false indicates that the browser is not supported and no state persists.

Back to top

Search Object

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

Method Return Type Description
.getNumResultsPerPage() Number

Gets the number of results in the result set.

Return value

  • resultSetSizeSetting, which is the number of results in the result set.
.gotoPage(page) None

Navigates directly to the specified results page.

Parameters

Name Description
page An integer that specifies the results page to which to navigate.

Return value

  • This method does not return a value.
.setLinkTarget(
  linkTarget)
None

Sets the link target for links embedded in search results (that is, the value of target= in the <a> tag.

Parameters

Name Description
linkTarget Supplies the target frame in which to open links; the following values are supported:
  • google.search.Search.LINK_TARGET_BLANK opens links in a new window (<a href=... target=_blank ...>). This is the default.
  • google.search.Search.LINK_TARGET_SELF opens links in the same window and frame (<a href=... target=_self ...>).
  • google.search.Search.LINK_TARGET_TOP opens links in the topmost frame (<a href=... target=_top ...>).
  • google.search.Search.LINK_TARGET_PARENT either opens links in the topmost frame, or replaces the current frame (<a href=... target=_parent ...>).
  • anything-else specifies that links open in the specified frame or window (<a href=... target=anything-else ...>).

Return value

  • This method does not return a value.
.setQueryAddition(term) None

Appends additional query parameters to the search.

Parameters

Name Description
term term is a string that specifies extra query terms to be appended to the search, as described in the opt_options parameter of CustomSearchControl.CustomSearchControl().

Return value

  • This method does not return a value.
.setResultSetSize(
  indicator)
None

Specifies the size of the result set.

Parameters

Name Description
indicator The size of the result set to display; the following values are supported:
  • An integer from 1 to 20 that indicates the number of results to display per page.
  • google.search.Search.SMALL_RESULTSET requests a small result set, typically 4 results per page for web searches, and 8 results per page for image searches.
  • google.search.Search.LARGE_RESULTSET requests a large result set, typically 8 results per page for web searches, and 16 results per page for image searches.
  • google.search.Search.FILTERED_CSE_RESULTSET requests up to 10 results per page for a maximum of 10 pages or 100 results.

Return value

  • This method does not return a value.

Back to top

ImageSearch Object

The google.search.ImageSearch object extends google.search.Search. This object implements the following methods and properties:

Method Return Type Description
.getLayout() String

Returns the image search result layout. See google.search.ImageSearch.setLayout() for the image search result layout values.

Return value

  • A string representing the image search result layout.
.setLayout() None

Specifies the image search result layout. The supported search result layout values are:

  • google.search.ImageSearch.LAYOUT_CLASSIC displays image results in classic layout.
  • google.search.ImageSearch.LAYOUT_POPUP displays image results in pop-up layout. It displays thumbnails as pop-up images on mouseover. This layout tries to scale pop-up images to their full width, but limits their height.
  • google.search.ImageSearch.LAYOUT_COLUMN displays image results in column layout. This layout tries to scale the preview images to their full height, but limits their width.

Return value

  • This method does not return a value.
.setRestriction(
  type,
  opt_value)
None

Specifies the restrictions to be set on the image searcher. type is the category of restriction to be set, and opt_value is the restriction value.

Parameters

Name Description
type The type of restriction to be set:
  • google.search.Search.RESTRICT_SAFESEARCH sets the SafeSearch level.
  • google.search.ImageSearch.RESTRICT_IMAGESIZE sets the size of the image.
  • google.search.ImageSearch.RESTRICT_COLORIZATION sets the colorization type of the image.
  • google.search.ImageSearch.RESTRICT_COLORFILTER sets the color filter to be applied to the image.
  • google.search.ImageSearch.RESTRICT_FILETYPE sets the file type of the image.
  • google.search.ImageSearch.RESTRICT_IMAGETYPE sets the content type of the image.
  • google.search.ImageSearch.RESTRICT_RIGHTS sets the type of rights that apply to the image.
opt_value The value of the restriction specified by type:
  • The supported SafeSearch level values are:
    • google.search.Search.SAFESEARCH_OFF disables SafeSearch filtering.
    • google.search.Search.SAFESEARCH_MODERATE excludes sexually explicit video and images from search result pages, but does not filter results that might link to explicit content. This is the default SafeSearch setting for Google searches.
    • google.search.Search.SAFESEARCH_STRICT filters out sexually explicit video and images from search result pages, as well as results that might link to explicit content.
  • The image size values restrict the search to images of the following sizes:
    • google.search.ImageSearch.IMAGESIZE_SMALL
    • google.search.ImageSearch.IMAGESIZE_MEDIUM
    • google.search.ImageSearch.IMAGESIZE_LARGE
    • google.search.ImageSearch.IMAGESIZE_EXTRA_LARGE
  • The image colorization values restrict the search to images with the following colorization attributes:
    • google.search.ImageSearch.COLORIZATION_BLACK_AND_WHITE
    • google.search.ImageSearch.COLORIZATION_GRAYSCALE
    • google.search.ImageSearch.COLORIZATION_COLOR
  • The image color filter values restrict the search to images predominantly containing the following colors:
    • google.search.ImageSearch.COLOR_RED
    • google.search.ImageSearch.COLOR_ORANGE
    • google.search.ImageSearch.COLOR_YELLOW
    • google.search.ImageSearch.COLOR_GREEN
    • google.search.ImageSearch.COLOR_TEAL
    • google.search.ImageSearch.COLOR_BLUE
    • google.search.ImageSearch.COLOR_PURPLE
    • google.search.ImageSearch.COLOR_PINK
    • google.search.ImageSearch.COLOR_WHITE
    • google.search.ImageSearch.COLOR_GRAY
    • google.search.ImageSearch.COLOR_BLACK
    • google.search.ImageSearch.COLOR_BROWN
  • The image file type values restrict the search to images of the following file types:
    • google.search.ImageSearch.FILETYPE_JPG
    • google.search.ImageSearch.FILETYPE_PNG
    • google.search.ImageSearch.FILETYPE_GIF
    • google.search.ImageSearch.FILETYPE_BMP
  • The image content type values restrict the search to images containing the following types of content:
    • google.search.ImageSearch.IMAGETYPE_FACES
    • google.search.ImageSearch.IMAGETYPE_CLIPART
    • google.search.ImageSearch.IMAGETYPE_LINEART
    • google.search.ImageSearch.IMAGETYPE_NEWS
    • google.search.ImageSearch.IMAGETYPE_PHOTO
  • The image rights values restrict the search to images with the following rights attributes:
    • google.search.ImageSearch.RIGHTS_REUSE
    • google.search.ImageSearch.RIGHTS_COMMERCIAL_REUSE
    • google.search.ImageSearch.RIGHTS_MODIFICATION
    • google.search.ImageSearch.RIGHTS_COMMERCIAL_MODIFICATION

Examples

The following example shows how to limit search results to pages within a specific site:

var customSearchControl = new google.search.CustomSearchControl('012345678901234567890:abcdefghijk');
var imageSearcher = myCSC.getimageSearcher();
imageSearcher.setRestriction(
  google.search.Search.RESTRICT_EXTENDED_ARGS,
  {'as_sitesearch' : 'examplepetstore.com/lizards/'}
);
The following example shows how to restrict the image size to icons only:
imageSearcher.setRestriction(
  google.search.ImageSearch.RESTRICT_IMAGESIZE,
  google.search.ImageSearch.IMAGESIZE_SMALL
);

Return value

  • This method does not return a value.
.setResultSetSize(
  indicator)
None

Specifies the size of the result set.

Parameters

Name Description
indicator The size of the result set to display; the following values are supported:
  • An integer from 1 to 20 that indicates the number of results to display per page.
  • google.search.Search.SMALL_RESULTSET requests a small result set, typically 8 results per page.
  • google.search.Search.LARGE_RESULTSET requests a large result set, typically 16 results per page.
  • google.search.Search.FILTERED_CSE_RESULTSET requests up to 20 results per page for a maximum of 10 pages or 200 results.

Return value

  • This method does not return a value.

Back to top

WebSearch Object

The google.search.WebSearch object extends google.search.Search. This object implements the following methods and properties:

Method Return Type Description
.setRestriction(
  type,
  opt_value)
None

Specifies the restrictions to be set on the web searcher. type is the category of restriction to be set, and opt_value is the restriction value.

Parameters

Name Description
type The type of restriction to be set:
  • google.search.Search.RESTRICT_SAFESEARCH sets the SafeSearch level.
  • google.search.Search.RESTRICT_EXTENDED_ARGS specifies extended query parameters for filtering and sorting, as described in the XML API reference. In this case, set opt_value to a key-value pair such as {as_oq : 'Warsaw+Berlin'}.
opt_value The value of the restriction specified by type. The supported values are:
  • google.search.Search.SAFESEARCH_OFF disables SafeSearch filtering.
  • google.search.Search.SAFESEARCH_MODERATE excludes sexually explicit video and images from search result pages, but does not filter results that might link to explicit content. This is the default SafeSearch setting for Google searches.
  • google.search.Search.SAFESEARCH_STRICT filters out sexually explicit video and images from search result pages, as well as results that might link to explicit content.

Return value

  • This method does not return a value.

Examples

  • See ImageSearch.setRestriction() for examples.
.setResultSetSize(
  indicator)
None

Specifies the size of the result set.

Parameters

Name Description
indicator The size of the result set to display; the following values are supported:
  • An integer from 1 to 20 that indicates the number of results to display per page.
  • google.search.Search.SMALL_RESULTSET requests a small result set, typically 4 results per page.
  • google.search.Search.LARGE_RESULTSET requests a small result set, typically 8 results per page.
  • google.search.Search.FILTERED_CSE_RESULTSET requests up to 10 results per page for a maximum of 10 pages or 100 results.

Return value

  • This method does not return a value.

Back to top

DrawOptions Object

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

Method Return Type Description
.DrawOptions() google.search.
DrawOptions

Creates a new DrawOptions object. The default drawing mode is that both the search form (search box) and results are displayed in the same HTML element (such as a div). Autocompletion is disabled by default. By default, there is only one root element, which contains both the search form and search results.

Return value

  • This method does not return a value.
.enableSearchboxOnly(
  resultUrlPrefix,
  opt_queryParamName,
  opt_newWindow,
  opt_paramSeparator)
None

Enables a searchbox-only search. When the user submits a search query in the searchbox form, the results are displayed in a new web page, which opens at the specified resultUrl.

The result page URL is constructed as a concatenation of the result page prefix (resultUrlPrefix), then a separator character (opt_paramSeparator), then the query parameter name.

If the result page prefix does not contain a ?, one is added. For example, if your result page prefix is www.examplepetstore.com/results.html and the query value is abraham+lincoln, the result page URL becomes www.examplepetstore.com/results.html?q=abraham+lincoln.

If the result page prefix does contain a ? with a query parameter, you can specify additional query parameters by providing a parameter separator and parameter name. For example, if your result page prefix is www.exampledomain.com/results.html?num=20, the parameter separator is &, the query parameter is q, and the query value is washington, then the result page URL becomes www.examplepetstore.com/results.html?num=20&q=pennsylvania.

Parameters

Name Description
resultUrlPrefix A string specifying the URL prefix of the search result page. Google recommends that you not include opt_queryKeyword in resultUrlPrefix.
opt_queryParamName A string that specifies the query parameter name in the result URL. If you do not provide a value, the default q is used.
opt_newWindow A Boolean value. If true, the result page opens in a new browser window. If false, the result page opens in the current browser window.
opt_paramSeparator A string that specifies the separator character that is placed between the URL path and the query parameters. For example, you can specify a hash (#) instead of a question mark (?).

Return value

  • This method does not return a value.
.enableSearchResultsOnly() None

Displays search results without the search form.

Return value

  • This method does not return a value.
.setAutoComplete(enabled) None

Parameters

Name Description
enabled A Boolean value. If true, the Custom Search Element requests autocompletion on key events. If false, the Custom Search Element does not request autocompletion (this is the default).

Return value

  • This method does not return a value.
.setSearchFormRoot(element) None

Sets the root element for the search form. You can use the root element to draw the search form in a separate element from the search results. The search results are drawn in the element provided to CustomSearchControl.draw().

Parameters

Name Description
element A string specifying the element ID or the actual HTMLElement as the root element.

Return value

  • This method does not return a value.

Back to top

Data Renderer Object

The google.search.Csedr object represents the Custom Search Engine data renderer. This object implements the following methods and properties:

Method Return Type Description
.addOverride(prefix) Array.<string>

Specifies a prefix that overrides the default rendering.

Parameters

Name Description
prefix A string added to the list of default prefixes, overriding the previously existing prefixes. You must label IDs with a unique prefix such as mysite_. Call .addOverride() before .render() to make the specified prefix override the current one. See Data Rendering for more detailed information about how to use this element.

Example

The following code overrides previously used prefixes in the testMe element:

google.search.Csedr.addOverride('new_');
var nodes = google.search.Csedr.render('testMe');

Return value

  • A string array containing the updated override list.
.render(
  element,
  var_args)
DocumentFragment

Renders the result layout from a Custom Search.

Parameters

Name Description
element Specifies a node ID or a DOM node ID of the template, with the additional arguments supplied.
var_args An argument list. It specifies one or more additional arguments that augment or override the first arguments. A useful way to call this method is with the following format, which passes all the current variables, and adds the argument oneMore:
render(node, variables, {oneMore:value})
            

Return value

  • A snippet containing a list of child nodes.

Back to top

Back to top

Troubleshooting

If you encounter problems with your code:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. Google Chrome has a full set of developer tools. In Firefox, you can use the JavaScript console or the Firebug. In IE, you can use the Microsoft Script Debugger.
  • Search the discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

Creating your own search form

Google Custom Search no longer supports using an iframe to host a custom search engine on your page. However, you can still use a HTML form code to implement the search box on your site, like this:

<form id="cse-search-box" action="http://google.com/cse">
  <input type="hidden" name="cx" value="YOUR SEARCH ENGINE ID goes here" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" size="31" />
  <input type="submit" name="sa" value="Search" />
</form>
<img src="http://www.google.com/cse/images/google_custom_search_smwide.gif">

Note: Replace the text YOUR SEARCH ENGINE ID goes here in the above example code with your actual search engine ID.

The HTML form code is provided for your convenience only; Google Custom Search doesn't provide support on this issue. All free search engines must display Google branding.

To display autocompletions in your own form, use the attachAutoCompletionWithOptions method.

Method Return Type Description
.attachAutoCompletionWithOptions(
  cxId,
  input,
  submitActor,
  opt_options)
object

Specifies how autocompletions appear as the user types a query. Autocompletions will be rendered in a table which appears just below the input box. The example below specifies a search box that displays a suggestion table with a maximum of 3 suggested autocompletions, horizontally offset by 10px.

var autoCompletionOptions = {
  'maxCompletions' : 3,
  'styleOptions' : {
    'xOffset' : 10
}};

google.setOnLoadCallback(function() {
  google.search.CustomSearchControl.attachAutoCompletionWithOptions(
    cx, document.getElementById('searchText'), 'searchForm',
    autoCompletionOptions);
});
      

Parameters

Name Description
cxId String. The ID of the Custom Search Engine whose completion corpus should be queried as the user types.
input Element. The text input box which should be monitored for key presses to trigger completion requests.
submitActor Either the ID of HTML form or form element, or an object. For a form or form element, submit() is called when an autocompletion is selected and onsubmit(), if any, returns true. If the object has an execute(query) method, it is called; otherwise submit() is called.
opt_options An optional parameter that specifies the various options for the display of autocompletions. The following keys are supported:
  • autoCompleteOptions (object): Specifies options for the autocompletion matching. Available options are:
    • matchType. Specifies the autocompletion type. Accepted values are any, prefix, or ordered.
    • maxCompletions (number): The maximum completions (excluding promotions) to display in the autocompletion table.
    • maxPromotions (number): The maximum number of promotions to display in the autocompletion table. The valid range is from 0 to 3. If not set, the default is 3.
    • validLanguages (string): Optional. A comma-delimited list of language codes. If specified, autocompletions will only appear for listed languages. When this option is not specified, autocompletions will be displayed for all languages by default.
  • styleOptions (object). Specifies the style of the autocompletion table. Available options are:
    • xOffset (number)—the amount to add to the X coordinate of the autocompletion table
    • yOffset (number)—the amount to add to the Y coordinate of the autocompletion table
    • widthOffset (number)—the amount to add to the width of the autocompletion table

Return value

  • This method returns an object that includes the CustomSearchControl methods prefillQuery and getInputQuery, as follows:
    var x = google.search.CustomSearchControl.attachAutoCompletionWithOptions(...);
    ...
    x.prefillQuery('your query here');
    ...
    var currentContent = x.getInputQuery();
    

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.