使用搜尋小工具建立搜尋介面

搜尋小工具可為網路應用程式提供自訂搜尋介面。 實作時只需要最少的 HTML 和 JavaScript,並支援常見功能,例如分頁和切面。您也可以使用 CSS 和 JavaScript 自訂介面。

如需更多彈性,請使用 Query API。請參閱「使用 Query API 建立搜尋介面」。

建立搜尋介面

如要建構搜尋介面,請按照下列步驟操作:

  1. 設定搜尋應用程式。
  2. 為應用程式產生用戶端 ID。
  3. 為搜尋框和搜尋結果新增 HTML 標記。
  4. 在頁面上載入小工具。
  5. 初始化小工具。

設定搜尋應用程式

每個搜尋介面都需要在管理控制台中定義的搜尋應用程式。應用程式會提供查詢設定,例如資料來源、多面向和搜尋品質參數。

如要建立搜尋應用程式,請參閱「建立自訂搜尋功能」。

產生應用程式的用戶端 ID

除了「設定 Cloud Search API 的存取權」中的步驟,您還需要為網路應用程式產生用戶端 ID。

設定專案

設定專案時,請注意下列事項:

  • 選取「網路瀏覽器」用戶端類型。
  • 提供應用程式的原始 URI
  • 記下用戶端 ID。小工具不需要用戶端密鑰。

詳情請參閱「用戶端網頁應用程式的 OAuth 2.0」。

新增 HTML 標記

小工具需要下列 HTML 元素:

  • 搜尋框的 input 元素。
  • 用於錨定建議對話方塊的元素。
  • 搜尋結果的元素。
  • (選用) 用於 facet 控制項的元素。

這個程式碼片段會顯示由 id 屬性識別的元素:

serving/widget/public/with_css/index.html
<div id="search_bar">
  <div id="suggestions_anchor">
    <input type="text" id="search_input" placeholder="Search for...">
  </div>
</div>
<div id="facet_results"></div>
<div id="search_results"></div>

載入小工具

使用 <script> 標記加入載入器:

serving/widget/public/with_css/index.html
<!-- Google API loader -->
<script src="https://apis.google.com/js/api.js?mods=enable_cloud_search_widget&onload=onLoad" async defer></script>

提供 onload 回呼。載入器準備就緒後,請呼叫 gapi.load(),載入 API 用戶端、Google 登入和 Cloud Search 模組。

serving/widget/public/with_css/app.js
/**
* Load the cloud search widget & auth libraries. Runs after
* the initial gapi bootstrap library is ready.
*/
function onLoad() {
  gapi.load('client:auth2:cloudsearch-widget', initializeApp)
}

初始化小工具

使用 gapi.client.init()gapi.auth2.init() 初始化用戶端程式庫,並提供用戶端 ID 和 https://www.googleapis.com/auth/cloud_search.query 範圍。使用建構工具類別設定及繫結小工具。

初始化範例:

serving/widget/public/with_css/app.js
/**
 * Initialize the app after loading the Google API client &
 * Cloud Search widget.
 */
function initializeApp() {
  // Load client ID & search app.
  loadConfiguration().then(function() {
    // Set API version to v1.
    gapi.config.update('cloudsearch.config/apiVersion', 'v1');

    // Build the result container and bind to DOM elements.
    var resultsContainer = new gapi.cloudsearch.widget.resultscontainer.Builder()
      .setSearchApplicationId(searchApplicationName)
      .setSearchResultsContainerElement(document.getElementById('search_results'))
      .setFacetResultsContainerElement(document.getElementById('facet_results'))
      .build();

    // Build the search box and bind to DOM elements.
    var searchBox = new gapi.cloudsearch.widget.searchbox.Builder()
      .setSearchApplicationId(searchApplicationName)
      .setInput(document.getElementById('search_input'))
      .setAnchor(document.getElementById('suggestions_anchor'))
      .setResultsContainer(resultsContainer)
      .build();
  }).then(function() {
    // Init API/oauth client w/client ID.
    return gapi.auth2.init({
        'clientId': clientId,
        'scope': 'https://www.googleapis.com/auth/cloud_search.query'
    });
  });
}

設定變數:

serving/widget/public/with_css/app.js
/**
* Client ID from OAuth credentials.
*/
var clientId = "...apps.googleusercontent.com";

/**
* Full resource name of the search application, such as
* "searchapplications/<your-id>".
*/
var searchApplicationName = "searchapplications/...";

自訂登入體驗

使用者開始輸入內容時,小工具會提示登入。您可以透過網站專用的 Google 登入功能,享有個人化體驗。

直接授權使用者

使用「使用 Google 帳戶登入」功能監控及管理登入狀態。 本範例會在按鈕點擊時使用 GoogleAuth.signIn()

serving/widget/public/with_signin/app.js
// Handle sign-in/sign-out.
let auth = gapi.auth2.getAuthInstance();

// Watch for sign in status changes to update the UI appropriately.
let onSignInChanged = (isSignedIn) => {
  // Update UI to switch between signed in/out states
  // ...
}
auth.isSignedIn.listen(onSignInChanged);
onSignInChanged(auth.isSignedIn.get()); // Trigger with current status.

// Connect sign-in/sign-out buttons.
document.getElementById("sign-in").onclick = function(e) {
  auth.signIn();
};
document.getElementById("sign-out").onclick = function(e) {
  auth.signOut();
};

自動登入使用者

預先授權應用程式給貴機構使用者,簡化登入程序。這項功能也適用於 Cloud Identity Aware Proxy。請參閱「使用 Google 登入服務搭配 IT 應用程式」。

自訂介面

如要變更小工具的外觀,請按照下列步驟操作:

  • 使用 CSS 覆寫樣式。
  • 使用轉接程式裝飾元素。
  • 使用介面卡建立自訂元素。

使用 CSS 覆寫樣式

這個小工具包含自己的 CSS。如要覆寫,請使用祖先選取器提高特異性:

#suggestions_anchor .cloudsearch_suggestion_container {
  font-size: 14px;
}

請參閱「支援的 CSS 類別」參考資料。

使用轉接程式裝飾元素

建立並註冊轉接程式,在元素顯示前進行修改。這個範例會新增自訂 CSS 類別:

serving/widget/public/with_decorated_element/app.js
/**
 * Search box adapter that decorates suggestion elements by
 * adding a custom CSS class.
 */
function SearchBoxAdapter() {}
SearchBoxAdapter.prototype.decorateSuggestionElement = function(element) {
  element.classList.add('my-suggestion');
}

/**
 * Results container adapter that decorates suggestion elements by
 * adding a custom CSS class.
 */
function ResultsContainerAdapter() {}
ResultsContainerAdapter.prototype.decorateSearchResultElement = function(element) {
  element.classList.add('my-result');
}

在初始化期間註冊轉接頭:

serving/widget/public/with_decorated_element/app.js
// Build the result container and bind to DOM elements.
var resultsContainer = new gapi.cloudsearch.widget.resultscontainer.Builder()
  .setAdapter(new ResultsContainerAdapter())
  // ...
  .build();

// Build the search box and bind to DOM elements.
var searchBox = new gapi.cloudsearch.widget.searchbox.Builder()
  .setAdapter(new SearchBoxAdapter())
  // ...
  .build();

使用轉接程式建立自訂元素

實作 createSuggestionElementcreateFacetResultElementcreateSearchResultElement,建構自訂 UI 元件。本範例使用 HTML <template> 標記:

serving/widget/public/with_custom_element/app.js
/**
 * Search box adapter that overrides creation of suggestion elements.
 */
function SearchBoxAdapter() {}
SearchBoxAdapter.prototype.createSuggestionElement = function(suggestion) {
  let template = document.querySelector('#suggestion_template');
  let fragment = document.importNode(template.content, true);
  fragment.querySelector('.suggested_query').textContent = suggestion.suggestedQuery;
  return fragment.firstElementChild;
}

/**
 * Results container adapter that overrides creation of result elements.
 */
function ResultsContainerAdapter() {}
ResultsContainerAdapter.prototype.createSearchResultElement = function(result) {
  let template = document.querySelector('#result_template');
  let fragment = document.importNode(template.content, true);
  fragment.querySelector('.title').textContent = result.title;
  fragment.querySelector('.title').href = result.url;
  let snippetText = result.snippet != null ?
    result.snippet.snippet : '';
  fragment.querySelector('.query_snippet').innerHTML = snippetText;
  return fragment.firstElementChild;
}

註冊轉接程式:

serving/widget/public/with_custom_element/app.js
// Build the result container and bind to DOM elements.
var resultsContainer = new gapi.cloudsearch.widget.resultscontainer.Builder()
  .setAdapter(new ResultsContainerAdapter())
  // ...
  .build();

// Build the search box and bind to DOM elements.
var searchBox = new gapi.cloudsearch.widget.searchbox.Builder()
  .setAdapter(new SearchBoxAdapter())
  // ...
  .build();

自訂分面元素必須遵循下列規則:

  • 在可點擊元素中附加 cloudsearch_facet_bucket_clickable
  • 將每個 bucket 包裝在 cloudsearch_facet_bucket_container 中。
  • 維持回應中的 bucket 順序。

舉例來說,下列程式碼片段會使用連結而非核取方塊來顯示分面。

serving/widget/public/with_custom_facet/app.js
/**
 * Results container adapter that intercepts requests to dynamically
 * change which sources are enabled based on user selection.
 */
function ResultsContainerAdapter() {
  this.selectedSource = null;
}

ResultsContainerAdapter.prototype.createFacetResultElement = function(result) {
  // container for the facet
  var container = document.createElement('div');

  // Add a label describing the facet (operator/property)
  var label = document.createElement('div')
  label.classList.add('facet_label');
  label.textContent = result.operatorName;
  container.appendChild(label);

  // Add each bucket
  for(var i in result.buckets) {
    var bucket = document.createElement('div');
    bucket.classList.add('cloudsearch_facet_bucket_container');

    // Extract & render value from structured value
    // Note: implementation of renderValue() not shown
    var bucketValue = this.renderValue(result.buckets[i].value)
    var link = document.createElement('a');
    link.classList.add('cloudsearch_facet_bucket_clickable');
    link.textContent = bucketValue;
    bucket.appendChild(link);
    container.appendChild(bucket);
  }
  return container;
}

// Renders a value for user display
ResultsContainerAdapter.prototype.renderValue = function(value) {
  // ...
}

自訂搜尋行為

使用轉接程式攔截要求,藉此覆寫搜尋應用程式設定。 實作 interceptSearchRequest,在執行前修改要求。這個範例會將查詢限制在所選來源:

serving/widget/public/with_request_interceptor/app.js
/**
 * Results container adapter that intercepts requests to dynamically
 * change which sources are enabled based on user selection.
 */
function ResultsContainerAdapter() {
  this.selectedSource = null;
}
ResultsContainerAdapter.prototype.interceptSearchRequest = function(request) {
  if (!this.selectedSource || this.selectedSource == 'ALL') {
    // Everything selected, fall back to sources defined in the search
    // application.
    request.dataSourceRestrictions = null;
  } else {
    // Restrict to a single selected source.
    request.dataSourceRestrictions = [
      {
        source: {
          predefinedSource: this.selectedSource
        }
      }
    ];
  }
  return request;
}

註冊轉接程式:

serving/widget/public/with_request_interceptor/app.js
var resultsContainerAdapter = new ResultsContainerAdapter();
// Build the result container and bind to DOM elements.
var resultsContainer = new gapi.cloudsearch.widget.resultscontainer.Builder()
  .setAdapter(resultsContainerAdapter)
  // ...
  .build();

下列 HTML 用於顯示依來源篩選的選取方塊:

serving/widget/public/with_request_interceptor/index.html
<div>
  <span>Source</span>
  <select id="sources">
    <option value="ALL">All</option>
    <option value="GOOGLE_GMAIL">Gmail</option>
    <option value="GOOGLE_DRIVE">Drive</option>
    <option value="GOOGLE_SITES">Sites</option>
    <option value="GOOGLE_GROUPS">Groups</option>
    <option value="GOOGLE_CALENDAR">Calendar</option>
    <option value="GOOGLE_KEEP">Keep</option>
  </select>
</div>

下列程式碼會監聽變更、設定選取項目,並視需要重新執行查詢。

serving/widget/public/with_request_interceptor/app.js
// Handle source selection
document.getElementById('sources').onchange = (e) => {
  resultsContainerAdapter.selectedSource = e.target.value;
  let request = resultsContainer.getCurrentRequest();
  if (request.query) {
    // Re-execute if there's a valid query. The source selection
    // will be applied in the interceptor.
    resultsContainer.resetState();
    resultsContainer.executeRequest(request);
  }
}

您也可以在介面卡中實作 interceptSearchResponse,攔截搜尋回應。

釘選版本

  • API 版本:在初始化前設定 cloudsearch.config/apiVersion
  • 小工具版本:使用 gapi.config.update('cloudsearch.config/clientVersion', 1.1)

如果未設定,這兩項都會預設為 1.0。

舉例來說,如要將小工具固定在 1.1 版,請執行下列操作:

serving/widget/public/basic/app.js
gapi.config.update('cloudsearch.config/apiVersion', 'v1');

保護搜尋介面

遵循網頁應用程式安全防護最佳做法,尤其是防止點擊劫持

啟用偵錯功能

使用 interceptSearchRequest 啟用偵錯功能:

if (!request.requestOptions) {
  request.requestOptions = {};
}
request.requestOptions.debugOptions = {enableDebugging: true};
return request;