要在一个常用网站搜索,想必大部分人会这样:
而如果一个网站适配了浏览器的"站点搜索"(site search)特性,或者说添加了"开放搜索描述"(opensearch description),那么用户可以也通过以下方式进行搜索:
如果你需要频繁新打开页面在一个网站搜索,使用站点搜索方式来搜索通常可以节省时间。
以下步骤将以站点www.example.com为例,介绍如何将一个现有查单词的搜索功能集成到浏览器地址栏。
例如:search.osdx,放置在站点首页旁边
<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>Word Search</ShortName>
<Image type="image/x-icon" width="16" height="16">https://example.com/favicon.ico</Image>
<Url rel="results" type="text/html" method="GET" template="https://www.example.com/search?q={searchTerms}"/>
<Url rel="suggestions" type="application/x-suggestions+json" method="GET" template="https://www.example.com/api/search-suggestions?q={searchTerms}"/>
<Url rel="self" type="application/opensearchdescription+xml" template="https://www.example.com/search.osdx" />
</OpenSearchDescription>
服务器在提供search.osdx时最好使用标准的MIME “application/opensearchdescription+xml”,因此你需要修改服务端的配置文件设置扩展名.osdx的MIME type。实在不行使用MIME "application/xml"浏览器也认,这样的话把search.osdx扩展名换成为.xml即可。
注:
<Url rel="suggestions" ... />可选,用于提供搜索建议<Url rel="self" ... />可选,用于自动更新在服务端实现一个REST API接口GET /api/search-suggestions,其响应的MIME type应是application/x-suggestions+json,响应体格式如下
[
"ver",
[
"verge",
"vertical"
],
[
"[vɜːdʒ] n. 边缘,边际 || be o...",
"[ˈvɜːtɪkl] adj. 垂直的,直立的..."
],
[
"https://www.example.com/search?q=verge&utm_source=search-suggestion",
"https://www.example.com/search?q=vertical&utm_source=search-suggestion"
]
]
如果要给响应体的每部分命名/加标识符,那么使用JavaScript可以这样:
let q = 'ver';
let completions = [
"verge",
"vertical"
];
let descriptions = [
"[vɜːdʒ] n. 边缘,边际 || be o...",
"[ˈvɜːtɪkl] adj. 垂直的,直立的..."
];
let queryURLs = [
"https://www.example.com/search?q=verge&utm_source=search-suggestion",
"https://www.example.com/search?q=vertical&utm_source=search-suggestion"
];
let content = JSON.stringify([
q,
completions,
descriptions,
queryURLs
], null, 2);
在<head>中添加<link rel="search" ...>元素,也建议给<head>添加属性profile="http://a9.com/-/spec/opensearch/1.1/"以便于浏览器自动发现。
<head profile="http://a9.com/-/spec/opensearch/1.1/">
<link rel="search" type="application/opensearchdescription+xml" href="/search.osdx" title="Word Search" />
调试准备:你可以通过修改本机hosts文件来模拟线上环境,以便调试站点搜索。例如:在hosts文件中添加
127.0.0.1 www.example.com
待本地调试通过后,还原hosts文件。
以Chrome 102为例,操作步骤如下:
访问站点首页https://www.example.com
激活https://www.example.com的站点搜索功能
最近的Chrome浏览器对发现的站点搜索要求激活(Activate)才能用(之前则不必),在"设置"/“搜索引擎”/“管理搜索引擎和站点搜索”,在底部展开未激活的,找到www.example.com的那一行,并点击"激活"
新建标签页,输入example.com,或输入exam待自动补全提示为example.com时,按Tab键(此时地址栏左边会显示"搜索Word Search")。
键入关键词
若实现了搜索建议,则接口/api/search-suggestions会收到HTTP请求;若响应MIME/内容格式正确,则地址栏下方会显示搜索补全建议。
回车

以Firefox 102为例,操作步骤与Chrome 102大致相同,不同的是:
