The search widget provides a customizable search interface for web applications. The widget only requires a small amount of HTML and JavaScript to implement and enables common search features such as facets and pagination. You can also customize portions of the interface with CSS and JavaScript.
If you need more flexibility than offered by the widget, consider using the Query API. For information on creating a search interface with the Query API, refer to Creating a search interface with the Query API.
Build a search interface
Building the search interface requires several steps:
- Configure a search application
- Generate a client ID for the application
- Add HTML markup for the search box and results
- Load the widget on the page
- Initialize the widget
Configure a search application
Each search interface must have an search application defined in the admin console. The search application provides additional information for the query, such as the data sources, facets, and search quality settings.
To create a search application, refer to Create a custom search experience.
Generate a client ID for the application
In addition to the steps in Configure access to the Google Cloud Search API, you also must generate a client ID for the web application.
When you configure the project:
- Select the Web browser client type
- Provide the origin URI of your app.
- Note of the client ID that was created. You will need the client ID to complete the next steps. The client secret is not required for the widget.
For additional information, see OAuth 2.0 for Client-side Web Application.
Add HTML markup
The widget requires a small amount of HTML to function. You must provide:
- An
input
element for the search box. - An element to anchor the suggestion popup to.
- An element to contain the search results.
- (Optional) Provide an element to contain the facets controls.
The following HTML snippet shows the HTML for a search widget, where the
elements to be bound are identified by their id
attribute:
Load the widget
The widget is dynamically loaded via a loader script. To include
the loader, use the <script>
tag as shown:
You must provide an onload
callback in the script tag. The function is called
when the loader is ready. When the loader is ready, continue to load the widget
by calling gapi.load()
to load the API client, Google Sign-in, and Cloud Search modules.
The initializeApp()
function is called after all modules are
loaded.
Initialize the widget
First, initialize the client library by calling
gapi.client.init()
or gapi.auth2.init()
with your generated client ID
and the https://www.googleapis.com/auth/cloud_search.query
scope. Next, use
the gapi.cloudsearch.widget.resultscontainer.Builder
and
gapi.cloudsearch.widget.searchbox.Builder
classes to configure the widget
and bind it to your HTML elements.
The following example shows how to initialize the widget:
The above example references two variables for configuration defined as:
Customize the sign-in experience
By default, the widget prompts users to sign-in and authorize the app at the time they begin typing a query. You can use Google Sign-in for Websites to offer a more tailored sign-in experience for users.
Authorize users directly
Use Sign In With Google to monitor the sign-in state of the
user and sign-in or sign-out users as needed. For example, the following
example observes the isSignedIn
state to monitor sign-in changes and
uses the GoogleAuth.signIn()
method to initiate the sign-in from a button
click:
For additional details, see Sign-In with Google.
Automatically sign-in users
You can further streamline the sign-in experience by pre-authorizing the application on behalf of users in your organization. This technique is also useful if using Cloud Identity Aware Proxy to guard the application.
For additional information, see Use Google Sign-In with IT Apps.
Customize the interface
You can change the appearance of the search interface through a combination of techniques:
- Override the styles with CSS
- Decorate the elements with an adapter
- Create custom elements with an adapter
Override the styles with CSS
The search widget comes with its own CSS to style suggestion and result elements as well as the pagination controls. You can restyle these elements as needed.
During load, the search widget dynamically loads its default stylesheet. This occurs after application stylesheets are loaded, raising the priority of the rules. To ensure your own styles take precedence over the default styles, use ancestor selectors to increase the specificity of the default rules.
For example, the following rule has no effect if loaded in a static
link
or style
tag in the document.
.cloudsearch_suggestion_container {
font-size: 14px;
}
Instead, qualify the rule with the ID or class of the ancestor container declared in the page.
#suggestions_anchor .cloudsearch_suggestion_container {
font-size: 14px;
}
For a list of support classes and example HTML produced by the widget, see the Supported CSS classes reference.
Decorate the elements with an adapter
To decorate an element prior to to rendering, create and reigster an
adapter that implements one of the decorating methods such as
decorateSuggestionElement
or decorateSearchResultElement.
For example, the following adapters add a custom class to the suggestion and result elements.
To register the adapter when initializing the widget, use the setAdapter()
method of the respective Builder
class:
Decorators may modify the attributes of the container element as well as any child elements. Child elements may be added or removed during decoration. However, if making structural changes to the elements, consider creating the elements directly instead of decorating.
Create custom elements with an adapter
To create a custom element for a suggestion, facet container, or search result,
create and register an adapter that implements
createSuggestionElement
,
createFacetResultElement
,
or createSearchResultElement
repsectively.
The following adapters illustrate creating custom suggestion and search results
elements using HTML <template>
tags.
To regsiter the adapter when initializing the widget, use the setAdapter()
method of the respective Builder
class:
Creating custom facet elements with createFacetResultElement
is subject to several restrictions:
- You must attach the CSS class
cloudsearch_facet_bucket_clickable
to the element users click on to toggle a bucket. - You must wrap each bucket in a containing element with the CSS
class
cloudsearch_facet_bucket_container
. - You can't render the buckets in a different order than they appear in the response.
For example, the following snippet renders facets using links instead of check boxes.
Customize search behavior
Search application settings represent the default configuration for a search interface and are static. To implement dynamic filters or facets, such as allowing users to toggle data sources, you can override the search application settings by intercepting the search request with an adapter.
Implement an adapter with the
interceptSearchRequest
method to modify requests made to the
search API
prior to execution.
For example, the following adapter intercepts requests to restrict queries to a user-selected source:
To register the adapter when initializing the widget, use the
setAdapter()
method when building the ResultsContainer
The following HTML is used to display a select box for filtering by sources:
The following code listens for the change, sets the selection, and reexecutes the query if necessary.
You can also intercept the search response by implementing
interceptSearchResponse
in the adapter.
Pin the API version
By default the widget uses the latest stable version of the API. To lock in a
specific version, set the cloudsearch.config/apiVersion
configuration parameter
to the preferred version prior to initializing the widget.
The API version will default to 1.0 if unset or set to an invalid value.
Pin the widget version
To avoid unexpected changes to search interfaces, set the
cloudsearch.config/clientVersion
configuration parameter as shown:
gapi.config.update('cloudsearch.config/clientVersion', 1.1);
The widget version will default to 1.0 if unset or set to an invalid value.
Secure the search interface
Search results contain highly sensitive information. Follow best practices for securing web applications, particularly against clickjacking attacks.
For more information, see OWASP Guide Project
Enable debugging
Use interceptSearchRequest
to turn on debugging for the search widget. For example:
if (!request.requestOptions) {
// Make sure requestOptions is populated
request.requestOptions = {};
}
// Enable debugging
request.requestOptions.debugOptions = {enableDebugging: true}
return request;