设置界面
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Google Cloud Search 教程的这一页介绍了如何使用可嵌入的搜索 widget 设置自定义搜索应用。如需从本教程的开头开始学习,请参阅 Cloud Search 入门教程。
安装依赖项
如果连接器仍在为代码库编制索引,请打开新 shell 并继续在那里操作。
从命令行中,将目录更改为 cloud-search-samples/end-to-end/search-interface
。
如需下载运行 Web 服务器所需的依赖项,请运行以下命令:
npm install
创建搜索应用凭据
连接器需要服务账号凭据才能调用 Cloud Search API。如需创建凭据,请执行以下操作:
返回 Google Cloud 控制台。
在左侧导航栏中,点击凭据。
从创建凭据下拉列表中选择 OAuth 客户端 ID。系统随即会显示“创建 OAuth 客户端 ID”页面。
(可选)如果您尚未配置同意屏幕,请点击配置同意屏幕。系统会显示“OAuth 权限请求”界面。
点击内部,然后点击创建。系统会显示另一个“OAuth 权限请求”界面。
填写必填字段。如需了解更多说明,请参阅设置 OAuth 2.0 的“用户许可”部分。
点击应用类型下拉列表,然后选择网络应用。
在名称字段中,输入“tutorial”。
在已获授权的 JavaScript 来源 字段中,点击添加 URI。系统会显示一个空白的“URI”字段。
在 URI 字段中,输入 http://localhost:8080
。
点击创建。系统随即会显示“OAuth 客户端已创建”界面。
记下客户端 ID。此值用于在通过 OAuth2 请求用户授权时标识应用。此实现不需要使用客户端密钥。
点击确定。
创建搜索应用
接下来,在管理控制台中创建搜索应用。搜索应用是搜索界面及其默认配置的虚拟表示形式。
- 返回 Google 管理控制台。
- 点击“应用”图标。系统会显示“应用管理”页面。
- 点击 Google Workspace。系统随即会显示“Google Workspace 应用管理”页面。
- 向下滚动,然后点击 Cloud Search。系统随即会显示“Google Workspace 设置”页面。
- 点击搜索应用。系统会显示“搜索应用”页面。
- 点击黄色圆圈 +。系统随即会显示“创建新的搜索应用”对话框。
- 在显示名称字段中,输入“tutorial”。
- 点击创建。
- 点击新创建的搜索应用旁边的铅笔图标(“修改搜索应用”)。系统随即会显示“搜索应用详情”页面。
- 记下应用 ID。
- 点击数据源右侧的铅笔图标。
- 点击“教程”旁边的启用切换开关。此切换开关可为新创建的搜索应用启用教程数据源。
- 在“教程”数据源的右侧,点击显示选项。
- 检查所有方面。
- 点击保存。
- 点击完成。
创建凭据和搜索应用后,请更新应用配置以包含以下值:
- 在命令行中,将目录更改为 `cloud-search-samples/end-to-end/search-interface/public`。
- 使用文本编辑器打开
app.js
文件。
- 在文件顶部找到
searchConfig
变量。
- 将
[client-id]
替换为之前创建的 OAuth 客户端 ID。
- 将
[application-id]
替换为上一部分中记下的搜索应用 ID。
- 保存文件。
运行应用
运行以下命令以启动应用:
npm run start
查询索引
如需使用搜索 widget 查询索引,请执行以下操作:
- 打开浏览器,然后前往
http://localhost:8080
。
- 点击登录,以授权该应用代表您查询 Cloud Search。
- 在搜索框中输入查询内容(例如字词“测试”),然后按 Enter 键。该页面应显示查询结果以及用于浏览结果的属性和分页控件。
查看代码
其余部分将介绍如何构建界面。
微件和相关库分两个阶段加载。首先,加载引导脚本:
其次,脚本准备就绪后,系统会调用 onLoad
回调。然后,它会加载 Google API 客户端、Google 登录和 Cloud Search widget 库。
在加载所有必需的库后,应用的其余初始化工作由 initializeApp
处理。
处理授权
用户必须授权应用代表其进行查询。虽然 widget 可以提示用户进行授权,但您可以通过自行处理授权来获得更好的用户体验。
对于搜索界面,应用会根据用户的登录状态显示两种不同的视图。
在初始化期间,系统会启用正确的视图,并配置登录和退出事件的处理程序:
创建搜索界面
搜索 widget 需要少量 HTML 标记来表示搜索输入内容和保存搜索结果:
在初始化期间,微件会初始化并绑定到输入元素和容器元素:
恭喜,您已成功完成本教程!继续阅读清理说明。
上一个
下一个
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-29。
[null,null,["最后更新时间 (UTC):2025-08-29。"],[],[],null,["# Set up the user interface\n\nThis page of the Google Cloud Search tutorial shows how to set up a custom\nsearch application using the embeddable search widget.\nTo start from the beginning of this tutorial, refer to\n[Cloud Search getting started tutorial](/workspace/cloud-search/docs/tutorials/end-to-end).\n\nInstall dependencies\n--------------------\n\n1. If the connector is still indexing the repository, open a new shell and\n continue there.\n\n2. From the command line, change directory to\n `cloud-search-samples/end-to-end/search-interface`.\n\n3. To download the required dependencies for\n running the web server, run the following command:\n\n npm install\n\nCreate the search application credentials\n-----------------------------------------\n\nThe connector requires service account credentials to call the Cloud Search\nAPIs. To create the credentials:\n\n1. Return to the [Google Cloud console](https://console.cloud.google.com/apis/dashboard).\n\n2. In the left navigation, click **Credentials**.\n\n3. From the **Create credentials** drop-down list, select\n **OAuth client ID**. The \"Create OAuth client ID\" page appears.\n\n4. (Optional). If you haven't configured the consent screen, click\n **CONFIGURE CONSENT SCREEN**. The \"OAuth consent\" screen appears.\n\n 1. Click **Internal** and click **CREATE**. Another \"OAuth consent\" screen\n appears.\n\n 2. Fill out required fields. For further instructions, refer to the user\n consent section of\n [Setting up OAuth 2.0](https://support.google.com/cloud/answer/6158849).\n\n5. Click the **Application type** drop-down list and select **Web application**.\n\n6. In the **Name** field, enter \"tutorial\".\n\n7. In **Authorized JavaScript origins** field, click **ADD URI**. An empty\n \"URIs\" field appears.\n\n8. In the **URIs** field, enter `http://localhost:8080`.\n\n9. Click **CREATE**. The \"OAuth client created\" screen appears.\n\n10. Note the client ID. This value is used to identify the application when\n requesting user authorization with OAuth2. The client secret is not required\n for this implementation.\n\n11. Click **OK**.\n\nCreate the search application\n-----------------------------\n\nNext, create a search application in the admin console. The search application\nis a virtual representation of the search interface and its default\nconfiguration.\n| **Note:** These steps must be performed by a domain administrator.\n\n1. Return to the [Google Admin console](https://admin.google.com).\n2. Click the Apps icon. The \"Apps administration\" page appears.\n3. Click **Google Workspace**. The \"Apps Google Workspace administration\" page appears.\n4. Scroll down and Click **Cloud Search**. The \"Settings for Google Workspace\" page appears.\n5. Click **Search Applications**. The \"Search Appplications\" page appears.\n6. Click the round yellow **+**. The \"Create a new search application\" dialog appears.\n7. In the **Display name** field, enter \"tutorial\".\n8. Click **CREATE**.\n9. Click the pencil icon next to the newly-created search application (\"Edit search application\"). The \"Search application details\" page appears.\n10. Note the **Application ID**.\n11. To the right of **Data sources**, click the pencil icon.\n12. Next to \"tutorial,\" click the **Enable** toggle. This toggle enables the tutorial data source for the newly created search application.\n13. To the right of the \"tutorial\" data source, click **Display options**.\n14. Check all the facets.\n15. Click **SAVE**.\n16. Click **DONE**.\n\nConfigure the web application\n-----------------------------\n\nAfter creating the credentials and search app, update the application\nconfiguration to include these values as follows:\n\n1. From the command line, change directory to \\`cloud-search-samples/end-to-end/search-interface/public.'\n2. Open `app.js` file with a text editor.\n3. Find the `searchConfig` variable at the top of the file.\n4. Replace `[client-id]` with the previously created OAuth client ID.\n5. Replace `[application-id]` with the search application ID noted in the previous section.\n6. Save the file.\n\nRun the application\n-------------------\n\nStart the application by running this command: \n\n npm run start\n\nQuery the index\n---------------\n\nTo query the index using the search widget:\n\n1. Open your browser and navigate to `http://localhost:8080`.\n2. Click **sign in** to authorize the app to query Cloud Search on your behalf.\n3. In the search box, enter a query, such as the word \"test,\" and press **enter**. The page should display the query results along with facets and pagination controls to navigate the results.\n\nReviewing the code\n------------------\n\nThe remaining sections examine how the user interface is built.\n\n### Loading the widget\n\nThe widget and related libraries are loaded in two phases. First, the bootstrap\nscript is loaded: \nindex.html \n[View on GitHub](https://github.com/googleworkspace/cloud-search-samples/blob/master/end-to-end/search-interface/public/index.html) \n\n```html\n\u003cscript src=\"https://apis.google.com/js/api.js?mods=enable_cloud_search_widget&onload=onLoad\" async defer\u003e\u003c/script\u003e\n```\n\nSecond, the `onLoad` callback is called once the script is ready. It then loads\nthe Google API client, Google Sign-in, and the Cloud Search widget libraries. \napp.js \n[View on GitHub](https://github.com/googleworkspace/cloud-search-samples/blob/master/end-to-end/search-interface/public/app.js) \n\n```javascript\n/**\n * Load the cloud search widget & auth libraries. Runs after\n * the initial gapi bootstrap library is ready.\n */\nfunction onLoad() {\n gapi.load('client:auth2:cloudsearch-widget', initializeApp)\n}\n```\n\nThe remaining initialization of the app is handled by `initializeApp`\nonce all the required libraries are loaded.\n\n### Handling authorization\n\nUsers must authorize the app to query on their behalf. While the widget\ncan prompt users to authorize, you can achieve a better user experience\nby handling authorization yourself.\n\nFor the search interface, the app presents two different views depending\non the sign-in state of the user. \nindex.html \n[View on GitHub](https://github.com/googleworkspace/cloud-search-samples/blob/master/end-to-end/search-interface/public/index.html) \n\n```html\n\u003cdiv class=\"content\"\u003e\n \u003cdiv id=\"app\" hidden\u003e\n \u003cdiv id=\"header\"\u003e\n \u003cbutton id=\"sign-out\"\u003eSign-out\u003c/button\u003e\n \u003c/div\u003e\n \u003c!-- Markup for widget...--\u003e\n \u003c/div\u003e\n \u003cdiv id=\"welcome\" hidden\u003e\n \u003ch1\u003eCloud Search Tutorial\u003c/h1\u003e\n \u003cp\u003eSign in with your Google account to search.\u003c/p\u003e\n \u003cbutton id=\"sign-in\"\u003eSign-in\u003c/button\u003e\n \u003c/div\u003e\n\u003c/div\u003e\n```\n\nDuring initialization the correct view is enabled and the handlers for\nsign-in and sign-out events are configured: \napp.js \n[View on GitHub](https://github.com/googleworkspace/cloud-search-samples/blob/master/end-to-end/search-interface/public/app.js) \n\n```javascript\n/**\n * Initialize the app after loading the Google API client &\n * Cloud Search widget.\n */\nasync function initializeApp() {\n await gapi.auth2.init({\n 'clientId': searchConfig.clientId,\n 'scope': 'https://www.googleapis.com/auth/cloud_search.query'\n });\n\n let auth = gapi.auth2.getAuthInstance();\n\n // Watch for sign in status changes to update the UI appropriately\n let onSignInChanged = (isSignedIn) =\u003e {\n document.getElementById(\"app\").hidden = !isSignedIn;\n document.getElementById(\"welcome\").hidden = isSignedIn;\n if (resultsContainer) {\n resultsContainer.clear();\n }\n }\n auth.isSignedIn.listen(onSignInChanged);\n onSignInChanged(auth.isSignedIn.get()); // Trigger with current status\n\n // Connect sign-in/sign-out buttons\n document.getElementById(\"sign-in\").onclick = (e) =\u003e auth.signIn();\n document.getElementById(\"sign-out\").onclick = (e) =\u003e auth.signOut();\n\n // ...\n\n}\n```\n\n### Creating the search interface\n\nThe search widget requires a small amount of HTML markup for the search\ninput and to hold the search results: \nindex.html \n[View on GitHub](https://github.com/googleworkspace/cloud-search-samples/blob/master/end-to-end/search-interface/public/index.html) \n\n```html\n\u003cdiv id=\"search_bar\"\u003e\n \u003cdiv\u003e\n \u003cdiv id=\"suggestions_anchor\"\u003e\n \u003cinput type=\"text\" id=\"search_input\" placeholder=\"Search for...\"\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n\u003c/div\u003e\n\u003cdiv id=\"facet_results\" \u003e\u003c/div\u003e\n\u003cdiv id=\"search_results\" \u003e\u003c/div\u003e\n```\n\nThe widget is initialized and bound to the input and container elements\nduring initialization: \napp.js \n[View on GitHub](https://github.com/googleworkspace/cloud-search-samples/blob/master/end-to-end/search-interface/public/app.js) \n\n```javascript\ngapi.config.update('cloudsearch.config/apiVersion', 'v1');\nresultsContainer = new gapi.cloudsearch.widget.resultscontainer.Builder()\n .setSearchApplicationId(searchConfig.searchAppId)\n .setSearchResultsContainerElement(document.getElementById('search_results'))\n .setFacetResultsContainerElement(document.getElementById('facet_results'))\n .build();\n\nconst searchBox = new gapi.cloudsearch.widget.searchbox.Builder()\n .setSearchApplicationId(searchConfig.searchAppId)\n .setInput(document.getElementById('search_input'))\n .setAnchor(document.getElementById('suggestions_anchor'))\n .setResultsContainer(resultsContainer)\n .build();\n```\n\nCongratulations, you've successfully completed the tutorial! Continue on for\ncleanup instructions.\n\n[Previous](/workspace/cloud-search/docs/tutorials/end-to-end/setup-connector)\n[Next](/workspace/cloud-search/docs/tutorials/end-to-end/finish)"]]