Tuesday, May 25, 2010

Class Reference - Google AJAX Search API - Google Code

Class Reference - Google AJAX Search API - Google Code: "- Sent using Google Toolbar"

emlynoregan@gmail.com | My favorites | English | Sign out

Watch Google I/O keynotes live on May 19 and 20!

Google AJAX Search API

Class Reference

The Google AJAX Search API is a JavaScript API implemented in the following classes.

We've updated this documentation to make use of the AJAX API loader. This loader makes it easier to use multiple Google AJAX APIs on the same page and unifies the namespaces across them. If you don't want to change your code, that's fine -- it won't break and the old namespace will continue to work. We hope you'll choose to transition to the new loader and namespace, as we'll continue to extend it for future AJAX APIs.

Check to show old class name and namespace scheme (e.g. GwebSearch, GlocalSearch, etc.)

Table of Contents

The Search Control

GSearchControlgoogle.search.SearchControl

An instance of GSearchControlgoogle.search.SearchControl represents a single search control on a page. Each search control manages the presentation of the user interface object and the search mechanism for a selected set of searcher objects (objects which implement the GSearch google.search.Search interface).

GSearchControlgoogle.search.SearchControl - Constructor

Constructor Description

GSearchControl()google.search.SearchControl()

Creates a new search control object. The search control object is a container for searchers, objects which implement the GSearchgoogle.search.Search interface. The search control object is not operational until is has at least one searcher child. A search control is bound to an html container using the .draw() method. Note that searcher objects may not be added to a search control once its draw() method has been called.

The expected order of operations is:

  • sc = new GSearchControl()google.search.SearchControl();
  • sc.addSearcher();
  • sc.draw();

Once these steps have occurred, the search control is active and ready to begin performing searches.

GSearchControlgoogle.search.SearchControl - Methods

Method Description

.addSearcher(searcher, opt_options?)

This method adds a searcher object to the search control. Once added, the search control will coordinate the activities of the searcher. It will coordinate the execution of searches, handle the related search completion events, provide a location where results are to be rendered, and provide a ui for "keeping" or "clipping" search results.

The method accepts an optional GsearcherOptionsgoogle.search.SearchOptions object which is used to specify various searcher specific options:

  • searcher - supplies a searcher object
  • opt_options - if specified, supplies configuration options for this searcher
  • returns - n/a

.draw(element, opt_drawOptions?)

This method is the final step needed to activate a search control object. It may only be called once all searchers have been added into the search control. When called, this method produces the user interface and search result containers for each configured searcher, and then sets up the various linkages needed to coordinate parallel searches across all of the searchers.

The method requires that the caller supply an html block element, typically a div element which the control draws within. The control operates best when provided with at least 300px of width and will scale reasonably well down to ~250px.

The default user interface style is a linear style where the control inputs are at the top followed by a linear set of stacked results. Optionally, callers may request a tabbed user interface which works well when vertical real estate is at a premium.

  • element - supplies an html block element that acts as a container for the control
  • opt_drawOptions - if specified, supplies a GdrawOptionsgoogle.search.DrawOptions object which can be used to specify linear or tabbed drawing mode. The object can also be used to supply the search control with a text input element that should be used to capture query terms. If unspecified, a linear drawing mode is assumed and the control allocates and manages its own text input element.
  • returns - n/a

.setTimeoutInterval(timeoutInterval)

When an application is providing its own input control and asking the search control to use that, the search control uses an input timer to determine when to execute a search. Each time a user types into the search controls text input area, a countdown timer is initialized. When the timer executes, a search is requested. The time lag between the last keystroke and the initiation of a search is programmed using this API. Note: The default value of the control is GSearchControlgoogle.search.SearchControl.TIMEOUT_MEDIUM (about 500ms).

  • timeoutInterval - supplies the value for the timeoutInterval, the amount of time between the last keystroke and the execution of a resulting search. Valid values include:
    • GSearchControlgoogle.search.SearchControl.TIMEOUT_SHORT - used to specify a very short delay ~350ms.
    • GSearchControlgoogle.search.SearchControl.TIMEOUT_MEDIUM - used to specify a medium delay of ~500ms.
    • GSearchControlgoogle.search.SearchControl.TIMEOUT_LONG - used to specify a long delay ~700ms.
  • returns - n/a

.execute(opt_query?)

This method causes the search control to initiate a sequence of parallel searches across all of the searchers configured into the control. If the opt_query argument is supplied, its value is placed within the search controls input text box, and becomes the search expression for the parallel search. Otherwise, the current value of the search control input text box is used. Note: this method allows applications to automate portions of the search control. For example, an application could choose to automatically initiate a search whenever the user hovers over a word or phrase or makes some other application specific gesture.

As a side effect of this call, the current set of search results displayed, as well as the search results stored within each of the controlled searcher objects is cleared.

  • opt_query - supplies an optional search expression used by the ensuing search. If not specified, then the search expression present in the search control's text input box is used.
  • returns - n/a

.setOnKeepCallback(object, method, opt_keepLabel?)

This method is used to inform the search control that the caller would like to be notified when a user has selected for copy, one of the search results managed by the control. If this method is not called, then the user is not offered an opportunity to copy search results. If the method is called, each search result is annotated with a text link, underneath the search result. Clicking on this link will cause the specified method to be called on the specified object, passing in a GResultgoogle.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 in the language that the rest of the control is running in.

  • object - supplies an application level object that defines the context that the specified method will be called in.
  • method - supplies the method to call. For instance, if this method is called as .setOnKeepCallback(foo, MyObject.prototype.myKeephandler), when a user clicks on the keep label, a call to foo.myKeephandler() is called.
  • opt_keepLabel - supplies an optional text label that sits beneath each search result which, when clicked, triggers a callback into the specified object/method. Valid values include:
    • GSearchControlgoogle.search.SearchControl.KEEP_LABEL_SAVE - a label value of "save"
    • GSearchControlgoogle.search.SearchControl.KEEP_LABEL_KEEP - a label value of "keep"
    • GSearchControlgoogle.search.SearchControl.KEEP_LABEL_INCLUDE - a label value of "include"
    • GSearchControlgoogle.search.SearchControl.KEEP_LABEL_COPY - a label value of "copy" (default)
    • GSearchControlgoogle.search.SearchControl.KEEP_LABEL_BLANK - a blank label value is used, this works well when all you want is the copy graphic (selectable via css)
    • Any other value - the value passed becomes the label. The caller is responsible for localization.
  • returns - n/a

.setResultSetSize(switchTo)

This method is called to select the number of results returned by each of the searchers. Note, this is not a scalar. It is an enumeration that indicates either a small number of results, or a large number of results. In the future, this method may be enhanced to support medium and extra large result sets. From the sample applications, you have probably seen the more/less twiddle control at the top of the search control. This method is used by that twiddle control.

  • switchTo - supplies en enumeration which indicates the desired number of search results to return for each configured searcher. Valid values include:
    • GSearchgoogle.search.Search.LARGE_RESULTSET - request a large number of results (typically 8 results)
    • GSearchgoogle.search.Search.SMALL_RESULTSET - request a small number of results (typically 4 results)
    • google.search.Search.FILTERED_CSE_RESULTSET - request up to 10 results. This will only work for Web Search queries scoped to a Filter Custom Search engine, otherwise an error will be returned.
  • returns - n/a

.cancelSearch()

This method is used to tell the search control to ignore all incoming search result completions. The internal state used by this method is reset, to allow searches each time a new search is requested. The intended use of this method is to help applications cope with ui flashing that can occur as slow input triggers inadvertent searches. By using this method each time input is sensed, previous searches based on partial input can easily be ignored.

  • returns - n/a

.clearAllResults()

This method is used to clear all of the search results out of the search control.

  • returns - n/a

.setLinkTarget(linkTarget)

This method is called to set the link target used for links embedded in search results. The default value is GSearchgoogle.search.Search.LINK_TARGET_BLANK which specifies that links will open in a new browser window. When this method is called, a search control wide link target setting is established. This effects all searchers that are currently attached to the search control as well as all searchers that are subsequently added to the control.

.setSearchCompleteCallback(object, method)

This method is used to inform the search control that the caller would like to be notified when a search completes. Note, the granularity of this call is the searcher level, NOT the search control level. What this means is that if your search control contains 5 searchers and you execute a search, as each searcher completes, your callback will be called. Note also, that not all searches will result in completion so be careful not to code deadlocks where you assume that a single completion will occur for each search.

  • object - supplies an application level object that defines the context that the specified method will be called in.
  • method - supplies the method to call. For instance, if this method is called as .setSearchCompleteCallback(foo, MyObject.prototype.mySearchComplete), when a search completes, a call to foo.mySearchComplete(searchControl, searcher) is called. The first argument of the callback, searchControl supplies the search control, and the second argument searcher supplies the searcher object that just completed a search.
  • returns - n/a

.setSearchStartingCallback(object, method)

This method is used to inform the search control that the caller would like to be notified right before a search begins. Note, the granularity of this call is the searcher level, NOT the search control level. What this means is that if your search control contains 5 searchers and you execute a search, as each searcher is told to begin searching, your method will be called.

  • object - supplies an application level object that defines the context that the specified method will be called in.
  • method - supplies the method to call. For instance, if this method is called as .setSearchStartingCallback(foo, MyObject.prototype.mySearchStarting), when a search begins, a call to foo.mySearchStarting(searchControl, searcher, query) is called. The first argument of the callback, searchControl supplies the search control, the second argument searcher supplies the searcher that is about to start a search, and the third argument query supplies the query.
  • returns - n/a

.setNoResultsString(str)

Normally, when a search produces no results, the search control slot for the searcher is left empty. This method allows the caller to specify a string that supplies a default "result". The system contains a value of GSearchControlgoogle.search.SearchControl.NO_RESULTS_DEFAULT_STRING which you can use. This is a localized string that means "No Results" in all supported locales.

  • str - supplies a string value that is used when a search yields no results..
  • returns - n/a

GSearchControlgoogle.search.SearchControl - Static Methods

Static Method Description

.inlineCurrentStyle(node, opt_deep?)

This utility function is used to clone the current computed style for the specified html node (or tree if opt_deep is specified) and inline the current style into the node. In some instances this function is useful, mainly in conjunction with an on keep handler where the application wishes to preserve a set of html styles while passing a piece of html from one application to another, where the receiving application does not have the associated style sheet. The simplest example of this scenario is in the case of an email application where the email application is using the Google AJAX Search API to allow users to clip search results into a message composition window where they will be emailed as html to another user. The recipient's email application in some cases will have no knowledge of Google AJAX Search API and will therefore not normally carry its style sheet. To account for this, we provide this method so the originating email application can inline the current styles so that the recipient can read the message with full fidelity.

  • node - supplies and html node whose style should be inlined
  • opt_deep - if specified, the inline operation is recursive inlining the styles for the current node and its descendants.
  • returns - n/a

Note: this method is not currently implemented on the Safari web browser.

GSearchControl google.search.SearchControl - Public Properties

This object does not expose any public properties.

GSearchFormgoogle.search.SearchForm

Applications that use the GSearchgoogle.search.Search objects in standalone form, rather than under control of the GSearchControlgoogle.search.SearchControl will often have a need to capture and process user-generated search requests. The GSearchFormgoogle.search.SearchForm() object is a light weight object that is designed for exactly this use case. It provides applications with a text input element, a search button, an optional clear button, as well as all standard branding.

GSearchFormgoogle.search.SearchForm - Constructor

Constructor Description

GSearchFormgoogle.search.SearchForm(enableClear, element)

Creates a new search form object. The search form object supplies user interface elements, methods, properties, and callbacks designed to allow applications to control a collection of GSearchgoogle.search.Search() objects. The user interface and capabilities match whats available to applications using the GSearchControlgoogle.search.SearchControl()) (in fact, the GSearchControlgoogle.search.SearchControl() is internally based on this object.

The expected order of operations is:

  • sf = new GSearchFormgoogle.search.SearchForm(true/false, container);
  • sf.setOnSubmitCallback(object, method);
  • optional - sf.setOnClearCallback(object, method);

Once these steps have occurred, the search form is active and ready to begin receiving and processing user input.

The method accepts a required enableClear argument as well as a required element argument

  • enableClear - when true, the search form should contain a clear button, otherwise, no clear button is created
  • element - supplies the HTML node that should act as a container for this form

GSearchFormgoogle.search.SearchForm - Methods

Method Description

.setOnSubmitCallback(object, method)

This method registers an object/method combination that is called when the search form is "submitted". This event occurs when the user clicks on the search button, or when the user hits enter while focused on the text input element. When this occurs, the specified object becomes the active object and the specified method is called. The argument passed to the method is this search form.

A typical method might look like this:

App.prototype.onSubmit = function(form) {

if (form.input.value) {
this.localSearcher.execute(form.input.value);
}
return false;
}

Note in the above example that the search form is passed to the method, and that the method returns false indicating that it has processed the submit event.

  • object - supplies an application level object that defines the context that the specified method will be called in.
  • method - supplies the method to call. The method is passed a reference to this form and must return false.

.setOnClearCallback(object, method)

This method registers an object/method combination that is called when the clear button in the search form is pressed. It is an error to call this method if the search form was created without a clear button. When this occurs, the specified object becomes the active object and the specified method is called. The argument passed to the method is this search form.

A typical method might look like this:

App.prototype.onClear = function(form) {

this.myClearFunction();
return false;
}

Note in the above example that the search form is passed to the method, and that the method returns false indicating that it has processed the clear event.

  • object - supplies an application level object that defines the context that the specified method will be called in.
  • method - supplies the method to call. The method is passed a reference to this form and must return false.

.execute(opt_string?)

This method allows an application to "submit" the form. This involves optionally setting the form's text input element and then calling the registered on-submit callback method established using .setOnSubmitCallback().

  • opt_string - if present, supplies a string value that is placed in the form's text input element prior to invoking the on-submit callback method.
  • returns - n/a

GSearchFormgoogle.search.SearchForm - Static Methods

This object does not expose any static methods.

GSearchFormgoogle.search.SearchForm - Public Properties

The following collection of public properties are exposed by the google.search.SearchForm.

Property Description

.input

This property is the text input element for the form. Applications are free to read and write this property at will. Typical use is that in an on-submit callback handler, an application will read form.input.value and then process this string, typically by calling .execute() on a searcher under its control.

.userDefinedCell

The search form's internal structure is a pair of HTML tables. The upper table contains the text input element, the localized search button, and an optional clear button. The lower table contains an application specific free cell, the left hand cell in the table, as well as a right aligned set of Google branding, including both text and an image. This property, the .userDefinedCell property is the DOM node of the table cell designed to hold application specific content. An application is free to use this space to deposit information in close proximity to the search form and aligned with the standard Google branding.

Searchers

GSearchgoogle.search.Search

An instance of the GSearchgoogle.search.Search class provides the ability to execute searches and receive results from a specific search service. This object is not directly used; it is a base class which service-specific searchers inherit from. The methods and properties described below apply to all objects that inherit from this base class. Each of those objects may supply additional interfaces as well.

The expected usage of this object is in conjunction with the GSearchControlgoogle.search.SearchControl where the search control provides both user interface and coordination. That said, it is perfectly acceptable for you to use this object independently, but just make sure you are not attempting to share the same instance of a searcher object between your application logic and a search control object.

GSearchgoogle.search.Search - Constructor

Constructor Description

GSearchgoogle.search.Search()

Creates a new searcher object. Note: Since this is a base class, it is unlikely that applications will make direct use of this constructor and instead will use the constructor as a side effect of creating a service specific searcher object (e.g., GwebSearchgoogle.search.WebSearch).

GSearchgoogle.search.Search - Methods

Method Description

.setResultSetSize(indicator)

This method is called to select the number of results returned by this specific searcher. Note, this is not a scalar. It is an enumeration that indicates either a small number of results, or a large number of results. In the future, this method may be enhanced to support medium and extra large result sets.

  • indicator - supplies an enumeration which indicates the desired number of search results to return. Valid values include:
    • GSearchgoogle.search.Search.LARGE_RESULTSET - request a large number of results (typically 8 results)
    • GSearchgoogle.search.Search.SMALL_RESULTSET - request a small number of results (typically 4 results)
    • google.search.Search.FILTERED_CSE_RESULTSET - request up to 10 results. This will only work for Web Search queries scoped to a Filter Custom Search engine, otherwise an error will be returned.
  • returns - n/a

.getResultSetSize()

This method returns the current result set size, the value established by the previous method.

  • returns an enumeration which indicates the current number of search results to return. Valid values include:
    • GSearchgoogle.search.Search.LARGE_RESULTSET - large number of results (typically 8 results)
    • GSearchgoogle.search.Search.SMALL_RESULTSET - small number of results (typically 4 results)
    • google.search.Search.FILTERED_CSE_RESULTSET - up to 10 results (only available for Filtered Custom Search engines)

.clearResults()

Upon successful completion of a search, the searcher object holds on to a collection of search results which describe the outcome of a particular search. This method is used to reset the searcher, clearing out all results. This method is implicitly called prior to the execution of a new search.

  • returns - n/a

.execute(query)

This method is called to begin a new search. The query argument supplies the search term. Upon completion, the object becomes populated with the corresponding set of results, and the registered search completion handler is called.

  • query - supplies the query term used to perform the search
  • returns - n/a

.setSearchCompleteCallback(object, method, opt_arguments?)

This method is used to register an object and method to notify on the completion of a search. Applications may optionally pass in a context argument using opt_arguments which is then passed to the specified method.

  • object - supplies an application level object that defines the context that the specified method will be called in.
  • method - supplies the method to call. For instance, if this method is called as .setSearchCompleteCallback(foo, MyObject.prototype.mySearchCompleteHandler), when a search on this searcher completes, a call to foo.mySearchCompleteHandler(opt_arguments?) is called.
  • returns - n/a

.setUserDefinedLabel(label)

This method is used to set a user defined label that should be used when this searcher is added to a search control. By calling this function, the user defined label specified will be used in the result section header or tab instead of the standard, built in labels. Expected usage is in conjunction with site restricted searching where it is both appropriate and expected that applications will indicate that they have programmed in restrictions by changing the standard label.

  • label - supplies a user defined label that replaces "Web", "Blog", etc. in the results section header.
  • returns - n/a

.setUserDefinedClassSuffix(classSuffix)

This method is used to set a user defined class suffix for the search results section, and for the collection of search results produced by this searcher in the search control. The motivation for this method is to allow applications to set unique styling for the results and header of a particular set of search results. Assuming this method is called with a value of "siteSearch", a class of gsc-resultsRoot-siteSearch will be applied to the DIV element that wraps the header and results associated with this searcher. Note, this is in addition to the generic gsc-resultsRoot class.

  • classSuffix - supplies a user defined class suffix that is appended to gsc-resultsRoot-. This class is added to the DIV element that wraps the header and results associated with this searcher.
  • returns - n/a

.setLinkTarget(linkTarget)

This method is called to set the link target used for links embedded in search results. The default value is GSearchgoogle.search.Search.LINK_TARGET_BLANK which specifies that links will open in a new browser window. When a searcher is added to a search control, the search control makes an implicit call to this method using the current link target setting for the search control. This means that if your application needs a searcher to operate with a different link target setting than the setting established by the search control, you need to call this method after adding the searcher to the search control.

.setNoHtmlGeneration()

There are times when your application is not using the search control and is only using a small set of properties from a search result and you are displaying these in a highly customized format. When this is the case, a small optimization is available to your application. The searcher can be programmed to NOT generate an .html property leaving you with only the raw properties valid in a result.

  • n/a - no input arguments
  • returns - n/a

.getAttribution()

For some classes of searchers (e.g., GlocalSearchgoogle.search.LocalSearch()), there is a requirement that attribution be displayed alongside the set of search results. When using the search control, this is included in the search control logic "for free". If you are using a raw searcher, caputuring and presenting proper attribution is up to you. This method is designed to provide you with an attribution node (or null if no attribution is required) which you can then display appropriately.

The display of attribution is only required while actively displaying a set of search results immediately after a search. The following snippet demonstrates a simple use of this API.

var attribution = GlocalSearchgoogle.search.LocalSearch.getAttribution();

if (attribution) {
var el = document.getElementById("searchwell");
el
.appendChild(attribution);
}
  • n/a - no input arguments
  • returns - non-null : Attribution is required. The return value is an HTML node that should be added to your page somewhere near the current set of search results.
  • returns - null : no attribution is required

.setQueryAddition(term)

This method allows the caller to set (or clear) an optional, additional query term that is appended to all queries flowing through the searcher. Applications will typically use this to the provide alternative results with mild variations from the original search term. For example, assuming a GwebSearchgoogle.search.WebSearch() based searcher, calling this function as search.setQueryAddition("filetype:pdf");, and then executing a query for "google", will result in the following query "google filetype:pdf". When using this API, we highly recomend using .setUserDefinedLabel() so that you can indicate to your users that their query has been modified. This is the same general advice we give when using .setSiteRestriction(). Please visit our sample for more information.

  • term - supplies an expression that is appended to each query flowing through this searcher (note, you do not need to supply a space). When the value of term is "", the effect of this API is canceled; queries are not modified.
  • returns - n/a

.createResultHtml(result)

This method allows the caller to either create or re-generate the .html property of the specified result. Sometimes this is needed when the caller had previously used .setNoHtmlGeneration(), or when the caller is reloading a result object from its own storage system.

  • result - supplies a result object. It's .html property will be deleted and regenerated as a result of this call. If the result does not contain a .html property, one will be created.
  • returns - n/a

.gotoPage(page)

After a search completes, a cursor property may become visible on the searcher option. This is a function of the number of search results available as well as the capabilities of the underlying searcher. If the cursor property is present, then this method allows you to fetch another bundle of search results. Applications specify which page by using the page argument. This value is then used to index the cursor.pages array which ultimately is used to compute the value of the &start url argument.

  • page - supplies the page number of the results that the application wants. This value is range checked relative to the .cursor.pages property and no operation is performed if the page is out of range or if the underlying searcher does not have a cursor property.
  • returns - n/a

GSearchgoogle.search.Search - Static Methods

Static Method Description

.scaleImage(width, height, imageScaler, opt_img)

This method is a static helper function that you can use to proportionally scale an image. You pass in the width and height of the current image, as well as an imageScaler object (containing a .width and .height property) and the function will calculate and return a proportionally scaled imageScaler object. You can then use this object's .height and .width property to build an image element.

Internally, the GvideoSearchgoogle.search.VideoSearch object defines an image scaler which it uses to scale the thumbnails. It's designed to maintain a 4x3 aspect ratio and is defined as follows.

// imageScaling defaults 4x3 100x75 image

this.imageScaler = {width:100,height:75};

When building the thumbnail img element, it computes the scaled height and width of the thumbnail image as follows:

// scale the thumbnail image using the searcher's .imageScaler.

// By default this is a 4x3 100x75 image,
// but its settable using .setVideoResultsTbHeight as well
var scaled = GSearchgoogle.search.Search.scaleImage(result.tbWidth,
result
.tbHeight, this.imageScaler);

// scaled.height and scaled.width now contain
// the values needed to proportionally scale the thumbnail
  • width - the original width of the image
  • height - the original height of the image
  • imageScaler - an imageScaler object which specifies in its .height property and its .width property the desired height/width box that the image should fit within.
  • opt_img - supplies and optional img object. If specified, its .height and .width properties are set by this call.
  • returns - an imageScaler object whose .height and .width properties contain the dimensions of the proportionally scaled image

.getBranding(opt_element?, opt_orientation?)

This method is a static helper function that returns a "powered by Google" HTML DOM branding node to your application, and optionally attaches it to your document as the only child of the specified optional element. The purpose of this method is to ensure that your application has a simple way to comply with branding requirements in situations where using with the search form in the GSearchControlgoogle.search.SearchControl or in the GSearchFormgoogle.search.SearchForm is not appropriate for your application.

The branding node, by default, is designed for a horizontal orientation and works well underneath a search form, above or below a collection of results, etc. In some cases, a vertical orientation of the branding is needed. As an example of this, consider a vertically oriented Video Bar. In this case, since the branding needs are so narrow, vertical orientation of the branding is needed (see the "powered by Google" branding at the bottom of the Video Bar). This API by default delivers horizontal orientation, but as an application, you can easily request vertical.

  • opt_element - an optional argument which, if supplied, specifies the HTML DOM node that will be populated with a "powered by Google" branding element.
  • opt_orientation - an optional argument which, if supplied, specifies the orientation of the branding node. Valid values include:
    • GSearchgoogle.search.Search.HORIZONTAL_BRANDING - request horizontal orientation
    • GSearchgoogle.search.Search.VERTICAL_BRANDING - request vertical orientation
  • returns - a "powered by Google" HTML DOM node that you are free to attach or clone onto your document.

.setOnLoadCallback(handler)

This method is a static helper function that registers the specified handler function to be called once the document containing this call loads. Previous documentation recomended that you use the body element's onload attribute (e.g., ). While this is a fine way to go when you are in complete control of the page and all code loaded by the page, this approach can cause problems with some runtimes that destroy your body.onload handler. The setOnLoadCallback() approach does not have these problems and therefore is our recomended way of registiring a callback that calls your code upon document load (a point in time when the AJAX Search APIs are fully loaded and ready for use).

  • handler - a required function that will be called once the containing document is loaded and when the search API is ready for use.
  • returns - n/a

GSearchgoogle.search.Search - Properties

The following collection of public properties are exposed by all objects that implement this interface. Unless otherwise stated, these properties are assumed to be read-only.

Property Description

.results[]

This property contains an array of search result objects, one for each result. Each time a search executes, this property is cleared, and each time a search completes, the array is populated. If there are no results to report, the .length property of this array will be set to 0.

.cursor

This optional property is present once a search completes successfully. When present, the property specifies how an application can request additional search results for the current query term, the estimated result count, the current page, and the url that can be used to vector to a search results page hosted at Google. The property has the following structure:

  • .pages[] - supplies an array used by .gotoPage() in order to retrieve a bundle of results. Each entry in the array is an object with the following structure:
    • .start - supplies the value that will be used in the &start url argument to request a bundle of results
    • .label - supplies a text label associated with the entry e.g., "1", "2", "3", or "4"
  • .estimatedResultCount - supplies the estimated number of results that match the current query. Note that this value will not necessarily match the similar value thats visible on the Google.com search properties.
  • .currentPageIndex - supplies the index into the pages array of the current set of results.
  • .moreResultsUrl - supplies a url to a Google hosted search page that contains additional search results.
Note: The maximum number of results pages is based on the type of searcher. Local search supports 4 pages (or a maximum of 32 total results) and the other searchers (Blog, Book, Image, News, Patent, Video, and Web) support 8 pages (for a maximum total of 64 results).

GwebSearchgoogle.search.WebSearch

This object implements the GSearchgoogle.search.Search interface over the Google Web Search service. Upon completion of a search it delivers a collection of GwebResult objects.

GwebSearchgoogle.search.WebSearch - Constructor

Constructor Description

GwebSearchgoogle.search.WebSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google Web Search service.

GwebSearchgoogle.search.WebSearch - Methods

Method Description

.setSiteRestriction(site, opt_refinement, opt_moreResultsTemplate)

This method is used to restrict the set of web search results returned by this searcher. To restrict to www.amazon.com, simply call this method passing in a value of "www.amazon.com". To clear site restrictions, pass in a value of null. The following snippet demonstrates this setting of a set restriction to "amazon.com". A more complete sample is available at Site Restrictions Sample.

var siteSearch = new GwebSearchgoogle.search.WebSearch();

siteSearch
.setSiteRestriction("amazon.com");

This method also allows the caller to restrict searches to a Google Custom Search Engine. Instead of specifying a URL path to this method, pass in the Custom Search Engine ID. The following snippet demonstrates setting a site restriction to a custom search engine whose id is 000455696194071821846:reviews. A more complete sample is available at Custom Search Engine Sample.

var siteSearch = new GwebSearchgoogle.search.WebSearch();

siteSearch
.setSiteRestriction("000455696194071821846:reviews");

When used in this manner, an optional Custom Search Engine Refinement may be supplied using the opt_refinement. Using this mechanism you are able to site restrict to a subset of your search engine. The value specified in opt_refinement must match a Custom Search Engine Refinement label associated with the specified search engine (see the code snippet below). A more complete sample is available at Curriculum Search Sample.

var cseId = "017576662512468239146:omuauf_lfve";

var siteSearch = new GwebSearchgoogle.search.WebSearch();
siteSearch
.setSiteRestriction(cseId, "Lectures");

Custom search engines often include a customized search results landing page. In order to support this, when Custom Search Engine site restrictions are in effect, an optional opt_moreResultsTemplate value may be supplied. This specifies a URL template that will be used to generate the "More results" link at the bottom of a set of search results. The URL template must include a placeholder of "__QUERY__" and "__HL__". When generating the "More results" link, the system will replace these placeholders with the current query term and UI language. This sample demonstrates the use of this mechanism for the main, left hand tab: Curriculum Search Sample.

The latest addition to Custom Search Engines is the ability to use Linked Custom Search Engines. In order to support this, the site argument has been extended so that it supports all of the options and modes listed above, in addition to the new anonymous object mode of specifying a site restriction. When the site argument is an object, one of the following properties may be present (listed in priority order meaning that if you supply multiple properties, the first one that we test for, in the order listed below, wins):

  • siteUrl - The search is relative to the supplied url
  • cseId - The search is relative to the supplied custom search engine id (e.g., 000455696194071821846:reviews)
  • crefUrl - The search is relative to linked custom search engine pointed to by the supplied url. See this sample for details.

When either cseId or crefUrl is specified, an optional Custom Search Engine Refinement may be supplied using the opt_refinement. Using this mechanism you are able to site restrict to a subset of your search engine. The value specified in opt_refinement must match a Custom Search Engine Refinement label associated with the specified search engine (see the code snippet below).

searcher = new google.search.WebSearch();

searcher
.setSiteRestriction(
{
crefUrl
: "http://www.google.com/cse/samples/vegetarian.xml"
},
"recipes");
  • site - supplies a site restriction setting in the form of a partial url (e.g., "www.amazon.com", "google.com", etc.), or a custom search engine id (e.g., "000455696194071821846:reviews", "000455696194071821846:shopping", etc.) Alternatively, this can contain an anonymous object as described above.
  • opt_refinement - when site refers to a Custom Search Engine, the value of this optional argument specifies a Custom Search Engine Refinement
  • opt_moreResultsTemplate - when site refers to a Custom Search Engine, the value of this optional argument specifies a URL template that will be used to construct the "More results" link that appears underneath a set of search results in the search control. The URL template must include a placeholder of "__QUERY__" and "__HL__". When generating the "More results" link, the system will replace these placeholders with the current query term and UI language.
  • returns - n/a

.setRestriction(type, opt_value)

This method is used to specify or clear a restriction on the set of results returned by this searcher. In order to establish a restriction, both type and opt_value must be supplied and valid. In order to clear a restriction, supply a valid value for type and either specify null for the value of opt_value, or do not supply this. This API currently supports the following restriction types:

  • GSearchgoogle.search.Search.RESTRICT_SAFESEARCH - When this is specified as the value of type, the web search results will be restricted to images based on the safesearch value. Valid optional values for this type are as follows:
    • GSearchgoogle.search.Search.SAFESEARCH_STRICT - apply strict filtering for both explicit text and explicit images (the default behavior)
    • GSearchgoogle.search.Search.SAFESEARCH_MODERATE - apply filtering for explicit images
    • GSearchgoogle.search.Search.SAFESEARCH_OFF - do not apply safe search filtering
    The following code snippet demonstrates how to turn safe search filtering off.
    var searcher = new google.search.WebSearch();
    
    searcher
    .setRestriction(google.search.Search.RESTRICT_SAFESEARCH,
    google
    .search.Search.SAFESEARCH_OFF);
  • GSearchgoogle.search.Search.RESTRICT_EXTENDED_ARGS New Args! - When this is specified, the value is an object containing name value pairs where the name may be one of lr, gl, or filter and the value for each is the value associated with the cgi argument as documented below.

    For example, the following code seqence restricts a web searcher to German and turns off the duplicate content filter

    searcher = new google.search.WebSearch()
    
    searcher
    .setRestriction(google.search.Search.RESTRICT_EXTENDED_ARGS,
    { "lr" : "lang_de", "filter" : "0"});

GlocalSearchgoogle.search.LocalSearch

This object implements the GSearchgoogle.search.Search interface over the Google Local Search service. Upon completion of a search it delivers a collection of GlocalResult objects.

This object is designed to produce search results relative to a geographic region. The object provides an API that allows applications to scope this geographic region by supplying a location string (city/state, a zipcode, an address), or by providing a GLatLnggoogle.maps.LatLng() object (see Google Maps), or by providing a GMap2google.maps.Map2() object (see Google Maps). The preferred interface is either a GLatLnggoogle.maps.LatLng() or a GMap2google.maps.Map2(). You may have noticed in the samples the presence of a "set location" control in the stack of local search results. This UI is implemented through coordination between the search control, and this object. The map projected through the search control scopes all search results, and its initial value (center point) is established by programming this object. The search control does not maintain preferences on center point. This is the responsibility of the application using this API.

Note: If no location is specified, this object scopes search results to the San Francisco, CA area. A more elaborate default is certainly being considered, something that takes into account the geographic region of the user.

GlocalSearchgoogle.search.LocalSearch - Constructor

Constructor Description

GlocalSearchgoogle.search.LocalSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google Local Search service.

GlocalSearchgoogle.search.LocalSearch - Methods

Method Description

.setCenterPoint(location)

This method establishes a center point that is used to scope search results. It accepts a single variant which may be a string, a GMap2google.maps.Map2, or a GLatLnggoogle.maps.LatLng. In the case of a string, an attempt is made to resolve the string into a GLatLnggoogle.maps.LatLng.

  • location - supplies a center point designation used to scope local searches. this argument is a variant and may specify:
    • a GMap2google.maps.Map2 which is noted by the presence of a getCenter() property. When this is the case, the center point of the specified map is captured and then used to scope search results.
    • a GLatLnggoogle.maps.LatLng which is noted by the presence of an x property. When this is the case, the value of this point is captured and used as the center point to scope local searches.
    • a string which specifies an address by name. When this argument is presented, searches are scoped as if the user performed a Google Local Search specifying near location as part of their search expression. Note: The string location is resolved into a GLatLnggoogle.maps.LatLng asynchronously so if this method is used, searches are made relative to this location once the geocoding operation completes with success.
  • returns - n/a

.setAddressLookupMode(mode)

The default behavior of this searcher is to co-mingle address lookup results (e.g., NY, NY) with local search results. There are situations where this co-mingled approach is not the desired behavior. For instance, suppose the searcher is centered in Santa Barbara, CA and the user is searching for "Cava". With co-mingled results, the first search result is actually an address match against "Cava Close, Aberdeen City, AB15 UK". The second result is "Cava Restaurant & Bar". Using this method, applications are able to disable and enable address lookup producing either strictly search results, or address lookup results co-mingled with search results. In this case, if address lookup is disabled, the first result would be "Cava Restaurant & Bar".

  • mode - supplies the desired address lookup mode:
    • GlocalSearchgoogle.search.LocalSearch.ADDRESS_LOOKUP_DISABLED - Disable address lookup and only produce search results.
    • GlocalSearchgoogle.search.LocalSearch.ADDRESS_LOOKUP_ENABLED - Enable address lookup producing co-mingled results. This is the default.
  • returns - n/a

.setRestriction(type, opt_value)

This method is used to specify or clear a restriction on the set of results returned by this searcher. In order to establish a restriction, both type and opt_value must be supplied and valid. In order to clear a restriction, supply a valid value for type and either specify null for the value of opt_value, or do not supply this.

This API currently supports the following restriction types:

  • GSearchgoogle.search.Search.RESTRICT_TYPE - When this is specified as the value of type, supplying an opt_value of:
    • GlocalSearchgoogle.search.LocalSearch.TYPE_BLENDED_RESULT - return a mix of both KML results and normal, local listings and geocodes.
    • GlocalSearchgoogle.search.LocalSearch.TYPE_KMLONLY_RESULTS - return only KML results and geocode results.
    • GlocalSearchgoogle.search.LocalSearch.TYPE_LOCALONLY_RESULTS - return only LOCAL listing results results and geocode results (note: this is the default behavior and is identical to the historical behavior of the API).

This method accepts the following arguments:

  • type - supplies the type of restriction to establish:
    • GSearchgoogle.search.Search.RESTRICT_TYPE
  • opt_value - supplies the value for the specified restriction type. If the value is null, then the specified restriction is cleared and the default behavior is restored. Otherwise, the value must be valid relative to the value of type and, if so, establishes a restriction. See above.

GlocalSearchgoogle.search.LocalSearch - Static Methods

Static Method Description

.resizeStaticMapUrl(result, height, width, opt_zoom?)

This utility function is designed to resize the image associated with the staticMapUrl property of the specified result. Upon completion, this property is replaced with a new value that represents the re-sized static map image. An optional zoom parameter may be passed allowing both the size and zoom level to be manipulated by this method. The default size of a static map image is 150px x 100px with a moderate zoom level of GlocalSearchgoogle.search.LocalSearch.STATIC_MAP_ZOOM_DEFAULT. The Static Map Tile sample demonstrates one way to use this method (see the snippet below).

var img = document.createElement("img");

google
.search.LocalSearch.resizeStaticMapUrl(result, 80, 120);
img
.src = result.staticMapUrl;
img
.title = result.titleNoFormatting;
  • result - supplies the result object whose static map image is to be re-sized. Upon completion, the staticMapUrl property of this result object is modified.
  • height - supplies the height, in pixels, of the new image. Note, the default height is 100 pixels and the max height is 640 pixels.
  • width - supplies the width, in pixels, of the new image. Note, the default width is 150 pixels and the max width is 640 pixels.
  • opt_zoom - supplies an optional zoom level for the map. If no zoom level is specified, the value is unchanged, with the default value being GlocalSearchgoogle.search.LocalSearch.STATIC_MAP_ZOOM_DEFAULT. Valid values include GlocalSearchgoogle.search.LocalSearch.STATIC_MAP_ZOOM_CLOSEST to GlocalSearchgoogle.search.LocalSearch.STATIC_MAP_ZOOM_FARTHEST.
  • returns - the new value of staticMapUrl is returned.

.computeStaticMapUrl(results, height, width, opt_zoom?)

This utility function is designed to create a static map image from the caller supplied collection of points. The points may be in the form of a collection of search result objects, a collection of objects containing a numeric .lat and .lng property, or a collection of GLatLnggoogle.maps.LatLng objects. Only the first GlocalSearchgoogle.search.LocalSearch.STATIC_MAP_MAX_POINTS objects are considered for inclusion. The Static Map Tile sample demonstrates one way to use this method. In this sample, a static map is created from a collection of locations in northern europe. This default map is shown when there are no search results. When a search completes, a new map image is computed using the collection of search results.

// demonstrate computeStaticMapUrl with simple point array

this.worldPointsUrl = google.search.LocalSearch.computeStaticMapUrl(
worldPoints
,350, 400);
document
.getElementById("resultsImg").src =
this.worldPointsUrl;
...
var worldPoints = [
{ lat : 48.8565, lng : 2.3509 }, // paris
{ lat : 52.5238, lng : 13.4119}, // berlin
{ lat : 52.3738, lng : 4.8909}, // amsterdam
{ lat : 55.676294, lng : 12.568115}, // copenhagen
{ lat : 60.160791, lng : 24.952548}, // helsinki
{ lat : 59.332725, lng : 18.064454}, // stockholm
{ lat : 59.913820, lng : 10.738741} // oslo
];
  • results - supplies an array of objects to be plotted on on a static map image.
  • height - supplies the height, in pixels, of the new image. Note, the maximum height is 640 pixels.
  • width - supplies the width, in pixels, of the new image. Note, the maximum width is 640 pixels.
  • opt_zoom - supplies an optional zoom level for the map. If no zoom level is specified, the system computes an appropriate zoom level. If supplied, valid values include: GlocalSearchgoogle.search.LocalSearch.STATIC_MAP_ZOOM_CLOSEST to GlocalSearchgoogle.search.LocalSearch.STATIC_MAP_ZOOM_FARTHEST.
  • returns - the static map url for this collection of points.

GvideoSearchgoogle.search.VideoSearch

This object implements the GSearchgoogle.search.Search interface over the Google Video Search service. Upon completion of a search it delivers a collection of GvideoResult objects.

It is important to note that this searcher is designed to access both YouTube and Google Video. For the most part, the differences in the result format and player are minimal. In some cases, applications, through specialized query predicates, can directly access YouTube Channels and Special Feeds. The following YouTube only query predicates are supported

YouTube Query Predicates

Predicate Description
ytchannel:name-of-channel expression?

The ytchannel: predicate allows your application to perform a search and get only video results from the specified channel. For example, a search expression of ytchannel:BarackObamadotcomwill return a collection of videos from the BarackObamadotcom YouTube Channel. By providing an additional, optional expression right after the ytchannel directive, your application can search for the expression within the selected channel, e.g., ytchannel:BarackObamadotcom oil.

ytfeed:top_rated[.this_week | .this_month | .all_time]

The ytfeed:top_rated predicate allows your application to perform a search and get only video results from the "top rated" YouTube Feed. By using the .this_week, .this_month, or .all_time qualifier, the feed is scoped to the specified time period. Like ytchannel:, the ytfeed: predicate supports search within a feed e.g., ytfeed:top_rated.this_week news.

ytfeed:{most_viewed, recently_featured}[this_week | .this_month | .all_time]

The ytfeed:most_viewed and ytfeed:recently_featured predicates are identical to ytfeed:top_rated. They differ in that they target different YouTube special feeds.

GvideoSearchgoogle.search.VideoSearch - Constructor

Constructor Description

GvideoSearchgoogle.search.VideoSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google Web Search service.

GvideoSearchgoogle.search.VideoSearch - Methods

Method Description

.setResultOrder(orderBy)

The default behavior of this searcher is to return results ordered by their relevance. In some cases, it is useful to see results ordered by date. This method may be used to change the result order.

  • orderBy - supplies the desired result order:
    • GSearchgoogle.search.Search.ORDER_BY_RELEVANCE - This is the default and indicates that results should be returned in order of their relevance.
    • GSearchgoogle.search.Search.ORDER_BY_DATE - This value indicates that results should be returned in publication date order.
  • returns - n/a

GblogSearchgoogle.search.BlogSearch

This object implements the GSearchgoogle.search.Search interface over the Google Blog Search service. Upon completion of a search, it delivers a collection of GblogResultgoogle.search.BlogResult objects.

GblogSearchgoogle.search.BlogSearch - Constructor

Constructor Description

GblogSearchgoogle.search.BlogSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google Blog Search service.

GblogSearchgoogle.search.BlogSearch - Methods

Method Description

.setSiteRestriction(site)

This method is used to restrict the set of blog search results returned by this searcher. To restrict results to all blog results on blogspot.com, simply call this method with a value of "blogspot.com". To restrict results to the Nintendo DS blog on Live Journal, simply call with "http://community.livejournal.com/nintendo_ds/". To clear site restrictions, pass in a value of null.

  • site - supplies a site restriction setting e.g., "blogspot.com", "http://community.livejournal.com/nintendo_ds/", etc.
  • returns - n/a

.setResultOrder(orderBy)

The default behavior of this searcher is to return results ordered by their relevance. In some cases, it is useful to see results ordered by date. This method may be used to change the result order.

  • orderBy - supplies the desired result order:
    • GSearchgoogle.search.Search.ORDER_BY_RELEVANCE - This is the default and indicates that results should be returned in order of their relevance.
    • GSearchgoogle.search.Search.ORDER_BY_DATE - This value indicates that results should be returned in publication date order.
  • returns - n/a

GnewsSearchgoogle.search.NewsSearch

This object implements the GSearchgoogle.search.Search interface over the Google News service. Upon completion of a search it delivers a collection of GnewsSearchgoogle.search.NewsResult objects.

GnewsSearchgoogle.search.NewsSearch - Constructor

Constructor Description

GnewsSearchgoogle.search.NewsSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google News service.

GnewsSearchgoogle.search.NewsSearch - Methods

Method Description

.setSiteRestriction(site)

This method is used to restrict the set of news search results returned by this searcher. To restrict results to all news results from the Seattle Times, simply call this method with a value of "Seattle Times". To restrict results to results from CNN, simply call with "CNN". The pattern is that the title of the news source is separated by either spaces or underscore (e.g., "_"). To clear site restrictions, pass in a value of null.

  • site - supplies a site restriction setting e.g., "Seattle Times", "CNN", etc.
  • returns - n/a

.setResultOrder(orderBy)

The default behavior of this searcher is to return results ordered by their relevance. In some cases, it is useful to see results ordered by date. This method may be used to change the result order.

  • orderBy - supplies the desired result order:
    • GSearchgoogle.search.Search.ORDER_BY_RELEVANCE - This is the default and indicates that results should be returned in order of their relevance.
    • GSearchgoogle.search.Search.ORDER_BY_DATE - This value indicates that results should be returned in publication date order.
  • returns - n/a

.setRestriction(type, value)

This method is used to restrict the set of news search results returned by this searcher above and beyond normal site restrictions. The first argument, type specifies the type of restriction desired, and then the value is type specific. A value of null, always clears the selected restriction.

  • type - supplies the type of restriction. The only currently supported value is GSearchgoogle.search.Search.RESTRICT_EXTENDED_ARGS
  • value - supplies the value for the restriction, or null to clear the restriction. With a type of GSearchgoogle.search.Search.RESTRICT_EXTENDED_ARGS, this argument specifies an object containing name value pairs where the name may be one of geo, qsid, topic, or ned and the value for each is the value associated with the cgi argument as documented in the below.

    For example, the following code seqence restricts a news searcher to the business topic in the German edition of Google News:

    searcher = new google.search.NewsSearch()
    
    searcher
    .setRestriction(google.search.Search.RESTRICT_EXTENDED_ARGS,
    { "topic" : "b", "ned" : "de"});
  • returns - n/a

GbookSearchgoogle.search.BookSearch (experimental)

This object implements the GSearchgoogle.search.Search interface over the Google Book Search service. Upon completion of a search it delivers a collection of GbookResult objects.

GbookSearchgoogle.search.BookSearch - Constructor

Constructor Description

GbookSearchgoogle.search.BookSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google Book Search service.

GbookSearchgoogle.search.BookSearch - Methods

Method Description

.setRestriction(type, opt_value)

This method is used to specify or clear a restriction on the set of results returned by this searcher. In order to establish a restriction, both type and opt_value must be supplied and valid. In order to clear a restriction, supply a valid value for type and either specify null for the value of opt_value, or do not supply this.

This API currently supports the following restriction types:

  • GSearchgoogle.search.Search.RESTRICT_TYPE - When this is specified as the value of type, supplying an opt_value of GbookSearchgoogle.search.BookSearch.TYPE_FULL_VIEW_BOOKS will restrict the results to only "Full View Books". Supplying a value of GbookSearchgoogle.search.BookSearch.TYPE_ALL_BOOKS allows the searcher to return all books. Note, this is the default and the behavior in effect when the GSearchgoogle.search.Search.RESTRICT_TYPE restriction is cleared.
  • type - supplies the type of restriction to establish:
    • GSearchgoogle.search.Search.RESTRICT_TYPE
  • opt_value - supplies the value for the specified restriction type. If the value is null, then the specified restriction is cleared. Otherwise, the value must be valid relative to the value of type and, if so, establishes a restriction. See above.

GimageSearchgoogle.search.ImageSearch

This object implements the GSearchgoogle.search.Search interface over the Google Image Search service. Upon completion of a search it delivers a collection of GimageSearchgoogle.search.ImageSearch objects. Note: Results can be restricted to the LIFE photo archive by including source:life as part of the query (experimental).

GimageSearchgoogle.search.ImageSearch - Constructor

Constructor Description

GimageSearchgoogle.search.ImageSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google Image Search service.

GimageSearchgoogle.search.ImageSearch - Methods

Method Description

.setRestriction(type, opt_value)

This method is used to specify or clear a restriction on the set of results returned by this searcher. In order to establish a restriction, both type and opt_value must be supplied and be valid. In order to clear a restriction, supply a valid value for type and either specify null for the value of opt_value, or do not supply the opt_value argument.

This API currently supports the following restriction types:

  • GSearchgoogle.search.Search.RESTRICT_SAFESEARCH - When this is specified as the value of type, the image search results will be restricted to images based on the safesearch value. Valid optional values for this type are as follows:
    • GSearchgoogle.search.Search.SAFESEARCH_STRICT - apply strict filtering for both explicit text and explicit images
    • GSearchgoogle.search.Search.SAFESEARCH_MODERATE - apply filtering for explicit images (the default behavior)
    • GSearchgoogle.search.Search.SAFESEARCH_OFF - do not apply safe search filtering
    The following code snippet demonstrates how to turn safe search filtering off.
    var searcher = new google.search.ImageSearch();
    
    searcher
    .setRestriction(google.search.Search.RESTRICT_SAFESEARCH,
    google
    .search.Search.SAFESEARCH_OFF);
  • GimageSearchgoogle.search.ImageSearch.RESTRICT_IMAGESIZE - When this is specified as the value of type, the image search results will be restricted to images with certain pixel dimensions. Valid optional values for this type are as follows:
    • GimageSearchgoogle.search.ImageSearch.IMAGESIZE_SMALL - restrict to small images, icons
    • GimageSearchgoogle.search.ImageSearch.IMAGESIZE_MEDIUM - restrict to medium images
    • GimageSearchgoogle.search.ImageSearch.IMAGESIZE_LARGE - restrict to large images
    • GimageSearchgoogle.search.ImageSearch.IMAGESIZE_EXTRA_LARGE - restrict to extra large images
    The following code snippet demonstrates how to retrieve only icon sized images.
    var searcher = new google.search.ImageSearch();
    
    searcher
    .setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
    google
    .search.ImageSearch.IMAGESIZE_SMALL);
  • GimageSearchgoogle.search.ImageSearch.RESTRICT_COLORIZATION - When this is specified as the value of type, the image search results will be restricted to images with certain colorization. Valid optional values for this type are as follows:
    • GimageSearchgoogle.search.ImageSearch.COLORIZATION_GRAYSCALE - restrict to grayscale images
    • GimageSearchgoogle.search.ImageSearch.COLORIZATION_COLOR - restrict to color images
    The following code snippet demonstrates how to retrieve only grayscale images.
    var searcher = new google.search.ImageSearch();
    
    searcher
    .setRestriction(google.search.ImageSearch.RESTRICT_COLORIZATION,
    google
    .search.ImageSearch.COLORIZATION_GRAYSCALE);
  • GimageSearchgoogle.search.ImageSearch.RESTRICT_COLORFILTER (experimental)New! - When this is specified as the value of type, the image search results will be filtered based on the selected color. Valid optional values for this type are as follows:
    • GimageSearchgoogle.search.ImageSearch.COLOR_BLACK
    • GimageSearchgoogle.search.ImageSearch.COLOR_BLUE
    • GimageSearchgoogle.search.ImageSearch.COLOR_BROWN
    • GimageSearchgoogle.search.ImageSearch.COLOR_GRAY
    • GimageSearchgoogle.search.ImageSearch.COLOR_GREEN
    • GimageSearchgoogle.search.ImageSearch.COLOR_ORANGE
    • GimageSearchgoogle.search.ImageSearch.COLOR_PINK
    • GimageSearchgoogle.search.ImageSearch.COLOR_PURPLE
    • GimageSearchgoogle.search.ImageSearch.COLOR_RED
    • GimageSearchgoogle.search.ImageSearch.COLOR_TEAL
    • GimageSearchgoogle.search.ImageSearch.COLOR_WHITE
    • GimageSearchgoogle.search.ImageSearch.COLOR_YELLOW
    The following code snippet demonstrates how to filter on the color red.
    var searcher = new google.search.ImageSearch();
    
    searcher
    .setRestriction(google.search.ImageSearch.RESTRICT_COLORFILTER,
    google
    .search.ImageSearch.COLOR_RED);
  • GimageSearchgoogle.search.ImageSearch.RESTRICT_FILETYPE - When this is specified as the value of type, the image search results will be restricted to images only of a certain filetype, e.g. JPG. Valid optional values for this type are as follows:
    • GimageSearchgoogle.search.ImageSearch.FILETYPE_JPG - restrict to only jpeg images
    • GimageSearchgoogle.search.ImageSearch.FILETYPE_PNG - restrict to only png images
    • GimageSearchgoogle.search.ImageSearch.FILETYPE_GIF - restrict to only gif images
    • GimageSearchgoogle.search.ImageSearch.FILETYPE_BMP - restrict to only bmp images
    The following code snippet demonstrates how to retrieve only images of type PNG.
    var searcher = new google.search.ImageSearch();
    
    searcher
    .setRestriction(google.search.ImageSearch.RESTRICT_FILETYPE,
    google
    .search.ImageSearch.FILETYPE_PNG);
  • GimageSearchgoogle.search.ImageSearch.RESTRICT_IMAGETYPE (experimental) - When this is specified as the value of type, the image search results will be restricted to images of certain types. Valid optional values for this type are as follows:
    • GimageSearchgoogle.search.ImageSearch.IMAGETYPE_FACES - restrict to images with faces in them
    • GimageSearchgoogle.search.ImageSearch.IMAGETYPE_PHOTO - restrict to photos
    • GimageSearchgoogle.search.ImageSearch.IMAGETYPE_CLIPART - restrict to clipart images
    • GimageSearchgoogle.search.ImageSearch.IMAGETYPE_LINEART - restrict to images of line drawings
    The following code snippet demonstrates how to retrieve face images.
    var searcher = new google.search.ImageSearch();
    
    searcher
    .setRestriction(google.search.ImageSearch.RESTRICT_IMAGETYPE,
    google
    .search.ImageSearch.IMAGETYPE_FACES);
  • GimageSearchgoogle.search.ImageSearch.RESTRICT_RIGHTS - When this is specified as the value of type, the image search results will be restricted to images that are labeled with certain licenses. Valid optional values for this type are as follows:
    • GimageSearchgoogle.search.ImageSearch.RIGHTS_REUSE - restrict to images labeled for reuse
    • GimageSearchgoogle.search.ImageSearch.RIGHTS_COMERCIAL_REUSE - restrict to images labeled for commercial reuse
    • GimageSearchgoogle.search.ImageSearch.RIGHTS_MODIFICATION - restrict to images labeled for reuse with modification
    • GimageSearchgoogle.search.ImageSearch.RIGHTS_COMMERCIAL_MODIFICATION - restrict to images labeled for commercial reuse with modification
    The following code snippet demonstrates how to retrieve only images labeled for reuse with modification.
    var searcher = new google.search.ImageSearch();
    
    searcher
    .setRestriction(google.search.ImageSearch.RESTRICT_RIGHTS,
    google
    .search.ImageSearch.RIGHTS_MODIFICATION);

    Note: Images returned with this filter may still have conditions on the license for use. Please remember that violating copyright is strictly prohibited by the API Terms of Use. For more details, see this article.

So for a slightly more complete example, if you wanted to search for face images in grayscale of Carmen Electra that were only of type jpg, the following snippet demonstrates how to achive this.
var searcher = new google.search.ImageSearch();

searcher
.setRestriction(google.search.ImageSearch.RESTRICT_IMAGETYPE,
google
.search.ImageSearch.IMAGETYPE_FACES);
searcher
.setRestriction(google.search.ImageSearch.RESTRICT_FILETYPE,
google
.search.ImageSearch.FILETYPE_JPG);
searcher
.setRestriction(google.search.ImageSearch.RESTRICT_COLORIZATION,
google
.search.ImageSearch.COLORIZATION_GRAYSCALE);
searcher
.execute('Carmen Electra');

.setSiteRestriction(site)

This method is used to restrict the set of image search results returned by this searcher. To restrict to www.photobucket.com, simply call this method passing in a value of "www.photobucket.com". To clear site restrictions, pass in a value of null. The following snippet demonstrates this setting a set restriction to "photobucket.com". Note: This method restricts results to images found on pages at the given URL.

var siteSearch = new GimageSearchgoogle.search.ImageSearch();

siteSearch
.setSiteRestriction("photobucket.com");

GpatentSearchgoogle.search.PatentSearch

This object implements the GSearchgoogle.search.Search interface over the Google Patent Search service. Upon completion of a search it delivers a collection of GpatentResultgoogle.search.PatentResult objects.

GpatentSearchgoogle.search.PatentSearch - Constructor

Constructor Description

GpatentSearchgoogle.search.PatentSearch()

The constructor is used to create an instance of a searcher object designed to provide search results from the Google Patent Search service.

GpatentSearchgoogle.search.PatentSearch - Methods

Method Description

.setRestriction(type, opt_value)

This method is used to specify or clear a restriction on the set of results returned by this searcher. In order to establish a restriction, both type and opt_value must be supplied and valid. In order to clear a restriction, supply a valid value for type and either specify null for the value of opt_value, or do not supply this.

This API currently supports the following restriction types:

  • GSearchgoogle.search.Search.RESTRICT_TYPE - When this is specified as the value of type, supplying an opt_value of GpatentSearchgoogle.search.PatentSearch.TYPE_ISSUED_PATENTS will restrict the results to only patents that have been issued. Supplying a value of GpatentSearchgoogle.search.PatentSearch.TYPE_APPLICATIONS allows the searcher to return filed, but not yet issued patents. And finally, supplying a value of GpatentSearchgoogle.search.PatentSearch.TYPE_ANY_STATUS allows the searcher a mix of issued and filed patents. Note, this is the default and the behavior in effect when the GSearchgoogle.search.Search.RESTRICT_TYPE restriction is cleared.
  • type - supplies the type of restriction to establish:
    • GSearchgoogle.search.Search.RESTRICT_TYPE
  • opt_value - supplies the value for the specified restriction type. If the value is null, then the specified restriction is cleared. Otherwise, the value must be valid relative to the value of type and, if so, establishes a restriction. See above.

.setResultOrder(orderBy)

The default behavior of this searcher is to return results ordered by their relevance. In some cases, it is useful to see results ordered by date. This method may be used to change the result order.

  • orderBy - supplies the desired result order:
    • GSearchgoogle.search.Search.ORDER_BY_RELEVANCE - This is the default and indicates that results should be returned in order of their relevance.
    • GSearchgoogle.search.Search.ORDER_BY_DATE - This value indicates that results should be returned in applicationDate order using descending dates, where the newest patent is the first search result.
    • GSearchgoogle.search.Search.ORDER_BY_ASCENDING_DATE - This value indicates that results should be returned in applicationDate order using ascending dates, where the oldest patent is the first search result.
  • returns - n/a

Result Objects

Result objects are produced using a JSON encoding of server search requests. As a result, we have chosen not to implement formal Javascript objects, and instead dynamically create these objects from their serialized form. While there is no formal implementation of the objects, they exist, and we document them as if there was a backing Javascript implementation. The impact of all this is minimal. All that it means is that there is no named constructor. For each result, it's as if the system called new Object() and then proceeded to set formal properties on that object. The results are documented below in terms of their properties.

For all objects, there are two common properties:

  • .GsearchResultClass - specifies the type of result.
  • .html - supplies the root of an html element that may be cloned and attached somewhere into the application's DOM hierarchy.

Result Styling

The .html property discussed above is built with CSS styling in mind. As a result, each piece of semantic information is enclosed in HTML markup with an appropriate set of class markers. This allows you to use this HTML in conjunction with your own custom CSS rules that style the HTML to meet your needs.

As you will see in the sections that follow, each search result is enclosed in a div element marked with a generic search result class of gs-result, as well as a result type specific class e.g., gs-webResult, gs-localResult, etc. This structure allows you to easily define generic CSS rules that are applied to all results, as well as type specific rules.

In addition to this structure, when a result is managed by the GSearchControlgoogle.search.SearchControl, each result is enclosed in a div element marked with a generic search control result class of gsc-result, as well as a result type specific class e.g., gsc-webResult, gsc-localResult, etc. Each section of results is further wrapped in a div element marked with a generic search control results class of gsc-results, as well as a result type specific class e.g., gsc-webResult, gsc-localResult, etc.

The net result of this structure is the following skeleton:



class="gsc-results gsc-webResult">


class="gsc-result gsc-webResult">


class="gs-result gs-webResult">


...



class="gsc-results gsc-localResult">

class="gsc-results gsc-blogResult">

Result Object - Common Properties

Common Property Description

.GsearchResultClass

Indicates the "type" of result.

  • GwebSearchgoogle.search.WebSearch.RESULT_CLASS - indicates GwebResult
  • GlocalSearchgoogle.search.LocalSearch.RESULT_CLASS - indicates GlocalResult
  • GvideoSearchgoogle.search.VideoSearch.RESULT_CLASS - indicates GvideoResult
  • GblogSearchgoogle.search.BlogSearch.RESULT_CLASS - indicates GblogResult
  • GnewsSearchgoogle.search.NewsSearch.RESULT_CLASS - indicates GnewsResult
  • GbookSearchgoogle.search.BookSearch.RESULT_CLASS - indicates GbookResult
  • GimageSearchgoogle.search.ImageSearch.RESULT_CLASS - indicates GimageResult
  • GpatentSearchgoogle.search.PatentSearch.RESULT_CLASS - indicates GpatentResult

.html

Supplies the root of an html element that may be cloned and attached somewhere into the application's DOM hierarchy. We expect that this is the primary property that applications will be concerned with and that their typical interaction will involve cloning this node and attaching it into their DOM hierarchy. We expect that they will use css to control styling and to control which elements are displayed. For instance, we expect the following fragment to be common across all applications that wish to copy and paste search results delivered through the Google AJAX Search API.

// clone the .html node from the result

var node = result.html.cloneNode(true);

// attach the node into my dom
container
.appendChild(node);

GwebResult

This object is produced by the GwebSearchgoogle.search.WebSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GwebSearchgoogle.search.WebSearch.RESULT_CLASS.

GwebResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.unescapedUrl

Supplies the raw URL of the result.

.url

Supplies an escaped version of the above URL.

.visibleUrl

Supplies a shortened version of the URL associated with the result. Typically displayed in green, stripped of a protocol and path.

.title

Supplies the title value of the result.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.content

Supplies a brief snippet of information from the page associated with the search result.

.cacheUrl

Supplies a url to Google's cached version of the page responsible for producing this result. This property may be null indicating that there is no cache, and it might be out of date in cases where the search result has been saved and in the mean time, the cache has gone stale. For best results, this property should not be persisted.

GwebResult CSS Structure

The following fragment of HTML illustrates the structure of a Web Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to supress the "snippet", a CSS rule of #mycontrol .gs-webResult .gs-snippet { display : none; } would do the trick.

class="gs-result gs-webResult">


class="gs-title">
class="gs-title">

class="gs-snippet">



class="gs-visibleUrl gs-visibleUrl-short">

class="gs-visibleUrl gs-visibleUrl-long">


GlocalResult

This object is produced by the GlocalSearchgoogle.search.LocalSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GlocalSearchgoogle.search.LocalSearch.RESULT_CLASS.

GlocalResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.title

Supplies the title for the result. In some cases, the title and the streetAddress are the same. This typically occurs when the search term is a street address such as 1231 Lisa Lane, Los Altos, CA.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.url

Supplies a url to a Google Maps Details page associated with the search result.

.lat

Supplies the latitude value of the result. This may be used to construct a GPoint using the following code snippet:
p = new GPoint(parseFloat(result.lng), parseFloat(result.lat));

.lng

Supplies the longitude value of the result. This may be used to construct a GPoint using the following code snippet:
p = new GPoint(parseFloat(result.lng), parseFloat(result.lat));

.streetAddress

Supplies the street address and number for the given result. Note: In some cases, this property may be set to "" if the result has no known street address.

.city

Supplies the city name for the result. Note: In some cases, this property may be set to "".

.region

Supplies a region name for the result (e.g., in the U.S., this is typically a state abbreviation, in other regions it might be a province, etc.) Note: In some cases, this property may be set to "".

.country

Supplies a country name for the result. Note: In some cases, this property may be set to "".

.phoneNumbers[]

Supplies an array of phone number objects where each object contains a .type property and a .number property. The value of the .type property can be one of "main", "fax", "mobile", "data", or "".

.addressLines[]

Supplies an array consisting of the mailing address lines for this result, for instance: ["1600 Amphitheatre Pky", "Mountain View, CA 94043"] or ["Via del Corso, 330", "00186 Roma (RM), Italy"]. To correctly render an address associated with a result, either use the .html property of the result directly or iterate through this array and display each addressLine in turn.

.ddUrl

Supplies a url that can be used to provide driving directions from the center of the set of search results to this search result. Note, in some cases this property may be missing or null. Always wrap access within a a test of if (result.ddUrl && result.ddUrl != null).

.ddUrlToHere

Supplies a url that can be used to provide driving directions from a user specified location to this search result. Note, in some cases this property may be missing or null. Always wrap access within a a test of if (result.ddUrlToHere && result.ddUrlToHere != null).

.ddUrlFromHere

Supplies a url that can be used to provide driving directions from this search result to a user specified location. Note, in some cases this property may be missing or null. Always wrap access within a a test of if (result.ddUrlFromHere && result.ddUrlFromHere != null).

.staticMapUrl

Supplies a url to a static map image representation of the current result. The image is 150px wide by 100px tall with a single marker representing the current location. Expected usage is to hyperlink this image using the url property. The image may be resized using GlocalSearchgoogle.search.LocalSearch.resizeStaticMapUrl(). The Static Map Tile sample demonstrates one way to use this property.

.listingType

This property indicates the type of this result which can either be "local" in the case of a local business listing or geocode result, or "kml" in the case of a KML listing.

.content

For "kml" results, this property contains a content snippet associated with the KML result. For "local" results, this property is the empty string.

GlocalResult CSS Structure

The following fragment of HTML illustrates the structure of a Local Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to supress the "address", a CSS rule of #mycontrol .gs-localResult .gs-address { display : none; } would do the trick.

class="gs-result gs-localResult">


class="gs-title">
class="gs-title">



class="gs-snippet">


class="gs-address">
class="gs-street">

class="gs-city">

class="gs-region">

class="gs-country">


class="gs-phone">



class="gs-directions">
class="gs-directions">




class="gs-directions-to-from">
class="gs-label">

class="gs-secondary-link">
class="gs-secondary-link">

class="gs-spacer">

class="gs-secondary-link">
class="gs-secondary-link">



GvideoResult

This object is produced by the GvideoSearchgoogle.search.VideoSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GvideoSearchgoogle.search.VideoSearch.RESULT_CLASS.

GvideoResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.title

Supplies the title of the video result.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.content

Supplies a snippet style description of the video clip.

.url

Supplies the url of a playable version of the video result.

.published

Supplies the published date of the video (rfc-822 format).

.publisher

Supplies the name of the video's publisher, typically displayed in green below the video thumbnail, similar to the treatment used for visibleUrl in the other search result objects.

.duration

The approximate duration, in seconds, of the video.

.tbWidth

Supplies the width, in pixels, of the video thumbnail.

.tbHeight

Supplies the height, in pixels, of the video thumbnail.

.tbUrl

Supplies the url of a thumbnail image which visually represents the video.

.playUrl

If present, supplies the url of the flash version of the video that can be played inline on your page. To play this video simply create an element on your page using this value as the src attribute and using application/x-shockwave-flash as the type attribute. If you want the video to play right away, make sure to append &autoPlay=true to the url.

.author

If present, this property supplies the YouTube user name of the author of the video.

.viewCount

If present, this property supplies a count of the number of plays for this video.

.rating

If present, this property supplies the rating of the video on a scale of 1 to 5.

GvideoResult CSS Structure

The following fragment of HTML illustrates the structure of a Video Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to supress the "snippet", a CSS rule of #mycontrol .gs-videoResult .gs-snippet { display : none; } would do the trick.

class="gs-result gs-videoResult">










class="gs-image-box">

class="gs-text-box">
class="gs-text-box">

class="gs-title">
class="gs-title">

class="gs-snippet">

class="gs-publishedDate">

class="gs-publisher">
class="gs-publisher">




GblogResult

This object is produced by the GblogSearchgoogle.search.BlogSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GblogSearchgoogle.search.BlogSearch.RESULT_CLASS.

GblogResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.title

Supplies the title of the blog post returned as a search result.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.postUrl

Supplies the URL to the blog post referenced in this search result.

.content

Supplies a snippet of content from the blog post associated with this search result.

.author

Supplies the name of the author that wrote the blog post.

.blogUrl

Supplies the URL of the blog which contains the post. Typically, this URL is displayed in green, beneath the blog search result and is linked to the blog.

.publishedDate

Supplies the published date (rfc-822 format) of the blog post referenced by this search result.

GblogResult CSS Structure

The following fragment of HTML illustrates the structure of a Blog Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to supress the "snippet", a CSS rule of #mycontrol .gs-blogResult .gs-snippet { display : none; } would do the trick.

class="gs-result gs-blogResult">


class="gs-title">
class="gs-title">



class="gs-publishedDate">

class="gs-relativePublishedDate">


class="gs-snippet">

class="gs-visibleUrl">
class="gs-visibleUrl">


GnewsResult

This object is produced by the GnewsSearchgoogle.search.NewsSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GnewsSearchgoogle.search.NewsSearch.RESULT_CLASS.

GnewsResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.title

Supplies the title of the news story returned as a search result.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.unescapedUrl

Supplies the raw URL of the result.

.url

Supplies an escaped version of the above URL.

.clusterUrl

When a news result has a set of related stories, this URL is available and non-null. In this situation, the URL points to a landing page that points to all of the related stories.

.content

Supplies a snippet of content from the news story associated with this search result.

.publisher

Supplies the name of the publisher of the news story.

.location

Contains the location of the news story. This is a list of locations in most specific to least specific order where the components are separated by ",". Note, there may only be one element in the list. A typical value for this property is "Edinburgh,Scotland,UK" or possibly "USA".

.publishedDate

Supplies the published date (rfc-822 format) of the news story referenced by this search result.

.relatedStories[]

This property is optional. It only appears in a result when the story also has a set of closely related stories. In this case, the relatedStories[] array will be present. Each element within the array contains the following subset of properties whose meaning is as described above:

  • .title
  • .titleNoFormatting
  • .unescapedUrl
  • .url
  • .publisher
  • .location
  • .publishedDate

.image{}

This property is optional. It only appears in a result when the system has determined that there is a good image that represents the cluster of news articles related to this result. It's important to note the the image relates to the cluster of news articles, not just the article that acts as the primary article for this result. Given this, it's very important for your related user interface to not mis-represent the image. You must always display the news source of the article, and the news source of the image as they are often different. You will notice that on Google News, the image is displayed off to the side with full attribution to the source, and that it's hyper-linked to the article associated with the image, not the article associated with the current result.

This property is optional. It does not always exist. It's best to check for .image == undefined before interacting with the property. When the property is present, it contains the following sub-properties:

  • .title - supplies the title of the article associated with the image.
  • .titleNoFormatting - same as above but stripped of HTML formatting.
  • .url - supplies the URL of this image as it is found in the article.
  • .originalContextUrl - supplies the URL of the article that contains this image. The image, when displayed, should normally link through this URL.
  • .publisher - supplies the publisher of the news article containing the image. The suggested user interface is to display this under or in close proximity to the image, hyper linked through the .url property from above.
  • .tbUrl - supplies the URL of a thumbnail of the image.
  • .tbWidth - supplies the width of the image referenced above. The standard size of this image is 80 pixels wide and 50 pixels tall.
  • .tbHeight - supplies the height of the image referenced above. The standard size of this image is 80 pixels wide and 50 pixels tall.

.language

This property is optional. When present, it indicates the language of the news story.

GnewsResult (all quotes) - Properties

When your news search request makes use of the qsid argument to request quotes. The standard result format is altered to include quotes specific properties. In addition to the common properties described above, the following object specific properties are available.

Property Description

.GsearchResultClass

A value of GnewsSearch.quote indicates that this result contains quote related properties, not standard news result properties. The property set for these two result formats are very different, so it's advised that you pay close attention to this property whenever mixing standard and quote based news queries.

.unescapedUrl

Supplies the raw URL of the result.

.url

Supplies an escaped version of the above URL.

.author

Supplies the name of the person that the quote is attributed to.

.content

Supplies a snippet of content from the news story that includes the quotes.

.publisher

Supplies the name of the publisher of the news story.

GnewsResult CSS Structure

The following fragment of HTML illustrates the structure of a News Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to supress the "snippet", a CSS rule of #mycontrol .gs-newsResult .gs-snippet { display : none; } would do the trick.

class="gs-result gs-newsResult">


class="gs-title">
class="gs-title">

class="gs-publisher">



class="gs-publishedDate">

class="gs-relativePublishedDate">


class="gs-snippet">



class="gs-clusterUrl">
class="gs-clusterUrl">


GbookResult (experimental)

This object is produced by the GbookSearchgoogle.search.BookSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GbookSearchgoogle.search.BookSearch.RESULT_CLASS.

GbookResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.title

Supplies the title of the book.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.unescapedUrl

Supplies the raw URL of the result.

.url

Supplies an escaped version of the above URL.

.authors

Supplies the list of authors of the book.

.bookId

Supplies the identifier associated with the book. This is typically an ISBN.

.publishedYear

Supplies the year that the book was published.

.pageCount

Supplies the number of pages contained within the book.

.thumbnailHtml

Supplies an html dom node that represents a thumbnail image of the book's cover. Note, if you want to use this property correctly, you must clone node it (e.g., var cover = res.thumbnailHtml.cloneNode(true);). Also, note that if you have supressed HTML generation (using .setNoHtmlGeneration()), this property is not available.

GbookResult CSS Structure

The following fragment of HTML illustrates the structure of a Book Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to style the "page count" as bold, a CSS rule of #mycontrol .gs-bookResult .gs-pageCount { font-weight : bold; } would do the trick.

class="gs-result gs-bookResult">










class="gs-image-box">


class="gs-image-box gs-book-image-box">


class="gs-row1">
class="gs-pages">
class="gs-page-edge">





class="gs-text-box">
class="gs-text-box">

class="gs-title">
class="gs-title">

class="gs-author">

class="gs-publishedDate">

class="gs-pageCount">

class="gs-visibleUrl">
class="gs-visibleUrl">




GimageResult

This object is produced by the GimageSearchgoogle.search.ImageSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GimageSearchgoogle.search.ImageSearch.RESULT_CLASS.

GimageResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.title

Supplies the title of the image, which is usually the base filename.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.unescapedUrl

Supplies the raw URL of the image.

.url

Supplies an escaped version of the above URL.

.visibleUrl

Supplies a shortened version of the URL associated with the result, typically displayed in green and stripped of a protocol and path.

.originalContextUrl

Supplies the URL of the page containing the image.

.width

Supplies the width of the image in pixels.

.height

Supplies the height of the image in pixels.

.tbWidth

Supplies the width, in pixels, of the image thumbnail.

.tbHeight

Supplies the height, in pixels, of the image thumbnail.

.tbUrl

Supplies the url of a thumbnail image.

.content

Supplies a brief snippet of information from the page associated with the search result.

.contentNoFormatting

Supplies the same information as .content, only stripped of HTML formatting.

GimageResult CSS Structure

The following fragment of HTML illustrates the structure of an Image Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to style the "image size as" as bold, a CSS rule of #mycontrol .gs-imageResult .gs-size { font-weight : bold; } would do the trick.

class="gs-result gs-imageResult">

class="gs-text-box">
class="gs-snippet">

class="gs-size">

class="gs-visibleUrl">



GpatentResult

This object is produced by the GpatentSearchgoogle.search.PatentSearch object. It is available in that object's .results[] array.

This object is indicated by a .GsearchResultClass value of GpatentSearchgoogle.search.PatentSearch.RESULT_CLASS.

GpatentResult - Properties

In addition to the common properties described above, the following object specific properties are available.

Property Description

.title

Supplies the title of the patent result.

.titleNoFormatting

Supplies the title, but unlike .title, this property is stripped of html markup (e.g., , , etc.).

.content

Supplies a snippet style description of the patent.

.unescapedUrl

Supplies the raw URL of the result.

.url

Supplies an escaped version of the above URL.

.applicationDate

Supplies the application filing date of the patent (rfc-822 format).

.patentNumber

Supplies the patent number for issued patents, and the application number for filed, but not yet issued patents.

.patentStatus

Supplies the status of the patent which can either be "filed" for filed, but not yet issued patents, or "issued" for issued patents.

.assignee

Supplies the assignee of the patent.

.tbUrl

Supplies the url of a thumbnail image which visually represents the patent.

GpatentResult CSS Structure

The following fragment of HTML illustrates the structure of a Patent Search result's .html property. The purpose of this skeleton is to show you the major structural components so that you can alter the styling and display of a result. For instance, if you want to supress the "snippet", a CSS rule of #mycontrol .gs-patentResult .gs-snippet { display : none; } would do the trick.

class="gs-result gs-patentResult">










class="gs-image-box">

class="gs-text-box">
class="gs-text-box">

class="gs-title">
class="gs-title">

class="gs-patent-info gs-metadata">
class="gs-patent-number">

class="gs-publishedDate">

class="gs-author">



class="gs-snippet">




Flash and other Non-Javascript Environments

For Flash developers, and those developers that have a need to access the AJAX Search API from other Non-Javascript environments, the API exposes a simple RESTful interface. In all cases, the method supported is GET and the response format is a JSON encoded result set with embedded status codes. Applications that use this interface must abide by all existing terms of use. An area to pay special attention to relates to correctly identifying yourself in your requests. Applications MUST always include a valid and accurate http referer header in their requests. In addition, we ask, but do not require, that each request contains a valid API Key. By providing a key, your application provides us with a secondary identification mechanism that is useful should we need to contact you in order to correct any problems. Read more about the usefulness of having an API key

Developers are also encouraged to make use of the userip parameter (see below) to supply the IP address of the end-user on whose behalf you are making the API request. Doing so will help distinguish this legitimate server-side traffic from traffic which doesn't come from an end-user.

Like the core Javascript interface, this interface is exposed through a uniform URL containing a mix of both standard and searcher specific CGI arguments. Your application can use an http stack of it's choosing. The only requirements are that you must be able to construct a properly constructed URL with all necessary CGI arguments, that you send an http referer header that accurately identifies your application, and that you are able to process the JSON encoded response.

Standard URL Base Address'

Each search endpoint is accessed through a standard URL. The following table lists the URL used to access each service.

Searcher Base Url
Web Search http://ajax.googleapis.com/ajax/services/search/web
Local Search http://ajax.googleapis.com/ajax/services/search/local
Video Search http://ajax.googleapis.com/ajax/services/search/video
Blog Search http://ajax.googleapis.com/ajax/services/search/blogs
News Search http://ajax.googleapis.com/ajax/services/search/news
Book Search http://ajax.googleapis.com/ajax/services/search/books
Image Search http://ajax.googleapis.com/ajax/services/search/images
Patent Search http://ajax.googleapis.com/ajax/services/search/patentNew!

Standard URL Arguments

Each request contains a mix of standard URL arguments and an optional set of searcher specific arguments. This section describes the standard arguments that are uniform across all searchers and that convey virtually identical semantic information to each searcher. In some cases, an argument is optional. This is indicated with a ? following the name of the argument. In all cases, the value of a CGI argument must be properly escaped (e.g., via the functional equivalent of Javascript's encodeURIComponent() method).

The following table lists the standard URL arguments. Additional sections appear below that highlight searcher specific arguments.

Argument Example Description
q q=Paris%20Hilton This argument supplies the query, or search expression, that is passed into the searcher.
v v=1.0 This argument supplies protocol version number. The only valid value at this point in time is 1.0.
userip? userip=192.168.0.1 This argument supplies the IP address of the end-user on whose behalf the request is being made. Requests that include it are less likely to be mistaken for abuse. In choosing to utilize this parameter, please be sure that you're in compliance with any local laws, including any laws relating to disclosure of personal information being sent.
rsz? rsz=small This optional argument supplies the number of results that the application would like to recieve. A value of small indicates a small result set size or 4 results. A value of large indicates a large result set or 8 results. If this argument is not supplied, a value of small is assumed.
hl? hl=fr This optional argument supplies the host language of the application making the request. If this argument is not present then the system will choose a value based on the value of the Accept-Language http header. If this header is not present, a value of en is assumed.
key? key=your-key This optional argument supplies the application's key. If specified, it must be a valid key associated with your site which is validated against the passed referer header. The advantage of supplying a key is so that we can identify and contact you should something go wrong with your application. Without a key, we will still take the same appropriate measures on our side, but we will not be able to contact you. It is definitely best for you to pass a key.
start? start=4 This optional argument supplies the start index of the first search result. Each successful response contains a cursor object (see below) which includes an array of pages. The start property for a page may be used as a valid value for this argument. For reference, a sample cursor object is shown below:
"cursor": {

"pages": [
{ "start": "0", "label": 1 },
{ "start": "4", "label": 2 },
{ "start": "8", "label": 3 },
{ "start": "12","label": 4 } ],
"estimatedResultCount": "48758",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/search..."
}
callback? callback=foo This optional argument alters the standard response format. When supplied, instead of producing a simple JSON encoded object, the system produces a Javascript function call response where the value of callback specifies the name of the function called in the response.
callbackFunction(

{"responseData" : {
"results" : [],
"cursor" : {}
},
"responseDetails" : null | string-on-error,
"responseStatus" : 200 | error-code
});
context? context=bar This optional argument is related to the context argument. When both are supplied, the value of context alters the normal response format associated with callback. The new format is:
callbackFunction(

contextValue, // the context arg value
responseObject, // the collection of results and cursor
responseStatus, // 200 on success, non-200 on failure
errorDetails) // error string for non-200 response

Standard Response Format

As discussed briefly in the previous section, there are two major variations in the response format. When the callback and context arguments are not supplied, the response format is a simple JSON object:

{

"responseData" : {
"results" : [],
"cursor" : {}
},
"responseDetails" : null | string-on-error,
"responseStatus" : 200 | error-code
}

In the JSON fragment above, note that the responseData property contains a results array and an optional cursor. These are identical both semantically and structurally to the results returned through the JavaScript Searchers layer. The responseStatus property contains a value of 200 on success and a non-200 http error status code on failure. If there is a failure, responseDetails contains a diagnostic string.

By using the callback argument, applications can easily request a JavaScript callback::

callback({

"responseData" : {
"results" : [],
"cursor" : {}
},
"responseDetails" : null | string-on-error,
"responseStatus" : 200 | error-code
});

If the application supplies both callback and context arguments, the response is encoded as a JavaScript procedure call. In this mode of operation, the value of callback becomes the procedure call target, the value of context is passes as the first argument, the value of responseData from above is passes as the second argument, the response status is passed as the third argument, and the final argument is either null or a diagnostic string.

foo('bar',{

"results": [
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://en.wikipedia.org/wiki/Paris_Hilton",
"url": "http://en.wikipedia.org/wiki/Paris_Hilton",
"visibleUrl": "en.wikipedia.org",
"cacheUrl": "http://www.google.com/search?q\u003dcache:TwrPfhd22hYJ:en.wikipedia.org",
"title": "\u003cb\u003eParis Hilton\u003c/b\u003e - Wikipedia, the free encyclopedia",
"titleNoFormatting": "Paris Hilton - Wikipedia, the free encyclopedia",
"content": "In 2006, she released her debut album \u003cb\u003eParis\u003c/b\u003e..."
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.imdb.com/name/nm0385296/",
"url": "http://www.imdb.com/name/nm0385296/",
"visibleUrl": "www.imdb.com",
"cacheUrl": "http://www.google.com/search?q\u003dcache:1i34KkqnsooJ:www.imdb.com",
"title": "\u003cb\u003eParis Hilton\u003c/b\u003e",
"titleNoFormatting": "Paris Hilton",
"content": "Self: Zoolander. Socialite \u003cb\u003eParis Hilton\u003c/b\u003e was..."
},
...
],
"cursor": {
"pages": [
{ "start": "0", "label": 1 },
{ "start": "4", "label": 2 },
{ "start": "8", "label": 3 },
{ "start": "12","label": 4 }
],
"estimatedResultCount": "59600000",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/search?oe\u003dutf8..."
}
}
, 200, null)

Web Search Specific Arguments

The Web Search system supports a number of optional arguments which are all listed below:

Argument Description
cx? This optional argument supplies the unique id for the Custom Search Engine that should be used for this request (e.g., cx=000455696194071821846:reviews).
cref? This optional argument supplies the url of a linked Custom Search Engine specification that should be used to satisfy this request (e.g., cref=http%3A%2F%2Fwww.google.com%2Fcse%2Fsamples%2Fvegetarian.xml).
safe? This optional argument supplies the search safety level which may be one of:
  • safe=active - enables the highest level of safe search filtering
  • safe=moderate - enables moderate safe search filtering (default)
  • safe=off - disables safe search filtering
lr? This optional argument allows the caller to restrict the search to documents written in a particular language (e.g., lr=lang_ja). This list contains the permissible set of values.
filter? New! This optional argument controls turning on or off the duplicate content filter:
  • filter=0 - Turns off the duplicate content filter
  • filter=1 - Turns on the duplicate content filter (default)
gl? New! This optional argument allows the caller to tailor the results to a specific country. The value should be a valid country code (e.g. uk, de, etc.). If this argument is not present, then the system will use a value based on the domain used to load the API (e.g. http://www.google.com/jsapi). If the API loader was not used, a value of "us" is assumed.

Local Search Specific Arguments

The Local Search system supports a number of optional arguments which are all listed below:

Argument Description
sll? This optional argument supplies the search center point for a local search. It's value is a comma separated latitude/longitude pair, e.g., sll=48.8565,2.3509.
sspn? This optional argument supplies a bounding box that the local search should be relative to. When using a Google Map, the sspn value can be computed using: myMap.getBounds().toSpan().toUrlValue(); (e.g., sspn=0.065169,0.194149).
mrt? This optional argument specifies which type of listing the user is interested in. Valid values include:
  • blended - request KML, Local Business Listings, and Geocode results
  • kmlonly - request KML and Geocode results
  • localonly - request Local Business Listings and Geocode results
If this argument is not supplied, the default value of localonly is used.

Video Search Specific Arguments

The Video Search system supports a number of optional arguments which are all listed below:

Argument Description
scoring? This optional argument tells the video search system how to order results. Results may be ordered by relevance (which is the default) or by date. To select ordering by relevance, do not supply this argument. To select ordering by date, set scoring as scoring=d.

Blog Search Specific Arguments

The Blog Search system supports a number of optional arguments which are all listed below:

Argument Description
scoring? This optional argument tells the blog search system how to order results. Results may be ordered by relevance (which is the default) or by date. To select ordering by relevance, do not supply this argument. To select ordering by date, set scoring as scoring=d.

News Search Specific Arguments

The News Search system supports a number of optional arguments which are all listed below:

Argument Description
scoring? This optional argument tells the news search system how to order results. Results may be ordered by relevance (which is the default) or by date. To select ordering by relevance, do not supply this argument. To select ordering by date, set scoring as scoring=d.
geo? This optional argument tells the news search system to scope search results to a particular location. With this argument present, the query argument (q) becomes optional. Note, this is a very new feature and locally scoped query coverage is somewhat sparse. You must supply either a city, state, country, or zip code as in geo=Santa%20Barbara or geo=British%20Columbia or geo=Peru or geo=93108. Note that this optional argument cannot be used with the topic argument.
qsid? This optional argument tells the news search system to scope search results to include only quote typed results (rather than classic news article style results). With this argument present, the query argument (q) becomes optional. The value of this argument designates a prominent individual whose quotes have been recognized and classified by the Google News search service. For instance, Barack Obama has a qsid value of tPjE5CDNzMicmM and John McCain has a value of lE61RnznhxvadM. Note, this is a very new feature and we currently do not have a good search or descovery mechanism for these qsid values..
topic? This optional argument tells the news search system to scope search results to a particular topic. The value of the argument specifies the topic in the current or selected edition:
  • h - specifies the top headlines topic
  • w - specifies the world topic
  • b - specifies the business topic
  • n - specifies the nation topic
  • t - specifies the science and technology topic
  • el - specifies the elections topic
  • p - specifies the politics topic
  • e - specifies the entertainment topic
  • s - specifies the sports topic
  • m - specifies the health topic
A topic selection can only be used without a query. If both a query and topic are specified, the query will be ignored. It is also not possible to scope a topic using the geo argument.

Topics vary slightly from edition to edition. E.g., in African editions like Namibia or Zimbabwe(&ned=en_na, &ned=en_zw) the topic af is available and represents the African topic. In general, if you are viewing an edition of Google News and see a topic of interest, click on the topic header and view the &topic argument in the browser's address bar.

ned? This optional argument tells the news search system which edition of news to pull results from. Values include:
  • us - specifies the US edition
  • uk - specifies the UK edition
  • fr_ca - specifies the French Canadian edition
  • etc.
The best way to understand the available set of editions is to look at the edition links at the bottom of Google News. After clicking on an edition, note the value of &ned argument in the browser's address bar.

Book Search Specific Arguments (experimental)

The Book Search system supports a number of optional arguments which are all listed below:

Argument Description
as_brr? This optional argument tells the book search system to restrict the search to "full view" books, or all books. A value of as_brr=1 restricts the search to only those books that are viewable in full. The default case is all books and that is indicated by not specifying this argument.
as_list? This optional argument tells the book search system to restrict the search to the specified user-defined library.

Image Search Specific Arguments

The Image Search system supports a number of optional arguments which are all listed below. Additionally, results can be restricted to the LIFE photo archive by including source:life as part of the query, as in q=source%3Alife+query+terms (experimental).

Argument Description
safe? This optional argument supplies the search safety level which may be one of:
  • safe=active - enables the highest level of safe search filtering
  • safe=moderate - enables moderate safe search filtering (default)
  • safe=off - disables safe search filtering
imgsz? This optional argument tells the image search system to restrict the search to images of the specified size, where size can be one of:
  • imgsz=icon - restrict to small images
  • imgsz=small|medium|large|xlarge - restrict to medium images
  • imgsz=xxlarge - restrict to large images
  • imgsz=huge - restrict to extra large images
imgc? This optional argument tells the image search system to restrict the search to images of the specified colorization, where colorization can be one of:
  • imgc=gray - restrict to grayscale images
  • imgc=color - restrict to color images
imgcolor?New!
(experimental)
This optional argument tells the image search system to filter the search to images of the specified color:
  • imgcolor=black
  • imgcolor=blue
  • imgcolor=brown
  • imgcolor=gray
  • imgcolor=green
  • imgcolor=orange
  • imgcolor=pink
  • imgcolor=purple
  • imgcolor=red
  • imgcolor=teal
  • imgcolor=white
  • imgcolor=yellow
imgtype?
(experimental)
This optional argument tells the image search system to restrict the search to images of the specified type:
  • imgtype=face - restrict to images of faces
  • imgtype=photo - restrict to photos
  • imgtype=clipart - restrict to clipart images
  • imgtype=lineart - restrict to images of line drawings
as_filetype? This optional argument tells the image search system to restrict the search to images of the specified filetype, where filetype can be one of:
  • as_filetype=jpg - restrict to jpg images
  • as_filetype=png - restrict to png images
  • as_filetype=gif - restrict to gif images
  • as_filetype=bmp - restrict to bmp images
as_rights? This optional argument tells the image search system to restrict the search to images labeled with the given licenses, where rights can be one or more of:
  • as_rights=cc_publicdomain - restrict to images with the publicdomain label
  • as_rights=cc_attribute - restrict to images with the attribute label
  • as_rights=cc_sharealike - restrict to images with the sharealike label
  • as_rights=cc_noncommercial - restrict to images with the noncomercial label
  • as_rights=cc_nonderived - restrict to images with the nonderived label
These restrictions can be used together, both positively or negatively. For instance, to emulate the commercial use with modification license, set the following:
        &as_rights=(cc_publicdomain|cc_attribute|cc_sharealike).-(cc_noncommercial|cc_nonderived)

Note: Images returned with this filter may still have conditions on the license for use. Please remember that violating copyright is strictly prohibited by the API Terms of Use. For more details, see this article.

as_sitesearch? This optional argument tells the image search system to restrict the search to images within the specified domain, e.g., as_sitesearch=photobucket.com. Note: This method restricts results to images found on pages at the given URL.

Patent Search Specific Arguments

The Patent Search system supports a number of optional arguments which are all listed below:

Argument Description
as_psrg? This optional argument tells the patent search system to restrict the search to ONLY patents that having been issued, skipping all patents that have only been filed. When specified, that value must be 1 as in &as_psrg=1
as_psra? This optional argument tells the patent search system to restrict the search to ONLY patents that only been filed, skipping over all patents that have been issued. When specified, that value must be 1 as in &as_psrg=1
scoring? This optional argument tells the patent search system how to order results. Results may be ordered by relevance (which is the default) or by date. To select ordering by relevance, do not supply this argument. To select ordering by descending date where the newest result is first, set scoring as scoring=d. To select ordering by ascending date where the oldest result is first, set scoring as scoring=ad.

Searcher and Drawing Options

GsearcherOptionsgoogle.search.SearcherOptions

When adding a searcher to the search control, the GsearcherOptionsgoogle.search.SearcherOptions object may be specified. If it is, it supplies various options used to control certain aspects of the related searcher. This object is implemented mainly as a property bag which is only loosley connected to a certain class of searcher. Some of its properties apply uniformly to all searchers, while some apply only to specific types of searchers. It is up to the application to use this properly, setting the right options and using them in the proper way.

This object allows the caller to control the default expansion mode (i.e., how the search results are displayed in the searchers section upon search completion), where on the web page the search results are displayed, as well as a variety of searcher specific options. The fragment that follows demonstrates how to use the searcher options class to set searcher options.

// create a searcher options object

// set up for open expansion mode
// load a searcher with these options
var options = new GsearcherOptionsgoogle.search.SearcherOptions();
options
.setExpandMode(GSearchControlgoogle.search.SearchControl.EXPAND_MODE_OPEN);
searchControl
.addSearcher(new GwebSearchgoogle.search.WebSearch(), options);

Once a searcher options object has been used in an .addSearcher() call, changing its properties has an undefined effect. The intended use is to set up an options object, use it when adding a searcher, and then never touch it again.

GsearcherOptionsgoogle.search.SearcherOptions - Constructor

Constructor Description

GsearcherOptionsgoogle.search.SearcherOptions()

The constructor is used to create an instance of a searcher options object. This object provides various configuration settings used by the search control.

GsearcherOptionsgoogle.search.SearcherOptions - Methods

Method Description

.setExpandMode(expandMode)

This method is used to communicate to the searcher the desired expansion mode of results, upon search completion.

  • expandMode - supplies the expansion mode for the associated searcher results section. Valid values include:
    • GSearchControlgoogle.search.SearchControl.EXPAND_MODE_CLOSED - The results section is closed showing no results. Clicking on the twiddle allows the user to "open" the results section seeing all results returned for the current search.
    • GSearchControlgoogle.search.SearchControl.EXPAND_MODE_OPEN - The results section is open showing all results.
    • GSearchControlgoogle.search.SearchControl.EXPAND_MODE_PARTIAL - The results section is partially open showing a small fraction of the results. Typically this means that only a single result is displayed.
  • returns - n/a

.setRoot(element)

This method is used to instruct the search control to draw the search results for the associated searcher in the container element provided rather than in the default container allocated during the execution of the search controls' .draw() method.

  • element - Supplies an html container element, which is typically a div element, that the search control is to use as a container for the results for the associated searcher.
  • returns - n/a

.setVideoResultsTbHeight(height)

This method allows the caller to specify an alternate default scaling factor that is applied to video search results as they are displayed by the search control. Note, the height supplied has an impact on the resulting width of the video as well. The system maintains a 4x3 aspect ratio for videos so the resulting width of the video is height * 1.33. The result is an imageScaler object (see GSearchgoogle.search.Search.scaleImage). Using this function has an impact on the .gs-videoResult td div.gs-image-box CSS rule within gsearch.css, so make sure that if you are adjusting video sizes you make compatible changes to your over-ride of this rule.

  • height - supplies the maximum height, in pixels, that the video's thumbnail should be scaled to before rendering by the search control. A maximum value of 100px is enforced by the API.
  • returns - n/a

.setImageResultsTbHeight(height)

This method allows the caller to specify an alternate default scaling factor that is applied to image search results as they are displayed by the search control. Note, the height supplied has an impact on the resulting width of the image as well. The system maintains a 4x3 aspect ratio for images so the resulting width of the image is height * 1.33. The result is an imageScaler object (see GSearch.scaleImage). Using this function has an impact on the .gs-imageResult CSS rule (width property) as well as .gs-imageResult .gs-image-box CSS rule (height property). The default image dimensions are 112x84, hence the 114x86 CSS rules (2px larger to account for a 1px border). Make sure that if you are adjusting image sizes you make compatible changes to your over-ride of these rules.

  • height - supplies the maximum height, in pixels, that the images's thumbnail should be scaled to before rendering by the search control. A maximum value of 100px is enforced by the API.
  • returns - n/a

.setNoResultsString(str)

Normally, when a search produces no results, the search control slot for the searcher is left empty. This method allows the caller to specify a string that supplies a default "result". The system contains a value of GSearchControlgoogle.search.SearchControl.NO_RESULTS_DEFAULT_STRING which you can use. This is a localized string that means "No Results" in all supported locales.

  • str - supplies a string value that is used when a search yields no results..
  • returns - n/a

GdrawOptionsgoogle.search.DrawOptions

When asking a search control to draw, you must specify a container for the control to draw within. In addition to this required parameter, the search control's .draw() method also accepts an optional GdrawOptionsgoogle.search.DrawOptions object. This object allows applications to request linear or tabbed layout (with linear being the default). Additionally, this object allows the application to request that the "search form" (i.e., the input element, button, controls, etc.) associated with driving the search be decoupled from the set of search results. This is accomplished by using the .setSearchFormRoot() method and supplying a container of your own that should host the search form.

As a more advanced mode of the above, this object allows applications to request that the search control not create a search form at all and instead use an application supplied text input element. When this option is specified, the search control takes control of the input element, grabbing onkeyup and onpaste events. Over time the list of events that the control latches on to may change. By handing an input element to the search control, the application is simply claiming responsibility for placement of the element as well as styling. Once the input element has been handed to the control, the application should not interact with the element other than to read its value if needed.

The following fragment demonstrates how to use this object to request that the search control draw itself in "tabbed" mode.

// create a drawOptions object

var drawOptions = new GdrawOptionsgoogle.search.DrawOptions();
drawOptions
.setDrawMode(GSearchControlgoogle.search.SearchControl.DRAW_MODE_TABBED);
searchControl
.draw(element, drawOptions);

The following fragment demonstrates how to use this object to request that the search form be decoupled from the set of search results.

...

<div id="searchForm">Loading...div>
...
var searchFormElement = document.getElementById("searchForm");
var drawOptions = new GdrawOptionsgoogle.search.DrawOptions();
drawOptions
.setSearchFormRoot(searchFormElement);
searchControl
.draw(element, drawOptions);

GdrawOptions - Constructor

Constructor Description

GdrawOptionsgoogle.search.DrawOptions()

The constructor is used to create an instance of a draw options object. This object provides various configuration settings used by the search control during its draw phase. Specifically, it provides control over tabbed vs. linear mode, as well as providing an application with a way to hand an input element off to the search control. The default setting for a newly constructed draw options object is linear mode with search control owned/created text input element.

GdrawOptionsgoogle.search.DrawOptions - Methods

Method Description

.setInput(inputElement)

This method is used to hand an input element off to the search control. Instead of creating its own text input element for capturing search queries, the control will use this application provided input element.

When this option is specified, the search control takes control of the input element, grabbing onkeyup and onpaste events. Over time the list of events that the control latches on to may change. By handing an input element to the search control, the application is simply claiming responsibility for placement of the element as well as styling. Once the input element has been handed to the control, the application should not interact with the element other than to read its value if needed.

  • inputElement - supplies an input element that should be used by the search control.
  • returns - n/a

.setDrawMode(drawMode)

This method is used to instruct the search control to draw the search results in either "tabbed" or "linear" mode.

  • drawMode - A value of GSearchControlgoogle.search.SearchControl.DRAW_MODE_LINEAR is used to specify linear drawing mode. A value of GSearchControlgoogle.search.SearchControl.DRAW_MODE_TABBED is used to specify tabbed drawing mode.
  • returns - n/a

.setSearchFormRoot(element)

This method is used to indicate that you would like the "search form" placed in the DOM container specified by "element" rather than in its default location near the search results.

View example (searchformroot.html)

  • element - supplies a container that the "search form" will be placed within.
  • returns - n/a

GXXX - Properties

The following collection of public properties are exposed by this object. Unless otherwise stated, these properties are assumed to be read-only.

Property Description

.property

Description

.property

Description

.property

Description

.property

Description

GXXX

Description

GXXX - Constructor

Constructor Description

GXXX()

Description

GXXX - Methods

Method Description

.method()

description

  • arg - supplies a
  • returns - n/a

.method()

description

  • arg - supplies a
  • returns - n/a

.method()

description

  • arg - supplies a
  • returns - n/a

.method()

description

  • arg - supplies a
  • returns - n/a

No comments:

Post a Comment