更多搜索元素回调示例

本页面提供了各种使用搜索元素回调的示例。它们是对 Custom Search Element API 文档的“回调”部分中的示例的补充。

搜索启动回调函数示例

搜索开始回调可以在将查询用于搜索之前修改查询。可编程搜索引擎可配置为在查询中包含预先确定的字词,但此回调可以根据回调函数可用的任何信息修改查询。

以下 search start 回调使用星期几装饰每个查询。

搜索启动回调示例
<script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:g9ckaktfipe"></script>
const mySearchStartingCallback = (gname, query) => {
  const dayOfWeek = new Date().getDay();
  console.log(dayOfWeek);
  var days = {
        "0": "Sunday",
        "1": "Monday",
        "2": "Tuesday",
        "3": "Wednesday",
        "4": "Thursday",
        "5": "Friday",
        "6": "Saturday"
    };

    return query + ' ' + days[dayOfWeek];
};
// Install the callback.
window.__gcse || (window.__gcse = {});
  window.__gcse.searchCallbacks = {
    image: {
      starting: mySearchStartingCallback,
    },
    web: {
      starting: mySearchStartingCallback,
    },
};

在 HTML 中添加以下元素:

<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

呈现的结果回调示例

结果渲染回调适用于在填充结果后对网页进行修改。该库旨在让您可以轻松修改结果的显示方式,而无需回调完全负责呈现结果。

以下示例展示了不会对结果执行操作的两个结果渲染回调应用。

确定最后一个结果页

此“已呈现结果”回调会注意到我们显示的是最后一页结果,并弹出提醒来提醒用户已到达末尾。

<script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
myWebResultsRenderedCallback = function(){
    var searchresults= document.getElementsByClassName("gsc-cursor-page");
    var index= document.getElementsByClassName("gsc-cursor-current-page");
    if(index.item(0).innerHTML == searchresults.length){
       alert("This is the last results page");
    }
};

安装回调

window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  web: {
      // Since the callback is in the global namespace, we can refer to it by name,
      // 'myWebResultsRenderedCallback', or by reference, myWebResultsRenderedCallback.
      rendered: myWebResultsRenderedCallback,
  },
};

在 HTML 中添加以下元素:

<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>
增大“光标”链接的字体大小

呈现的结果回调演示增加了用于选择结果页面的“游标”数字的字体大小。

默认字体大小为 12 像素。在这里,我们将其增加到 20px。

<script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
myWebResultsRenderedCallback = function(){
   document.getElementsByClassName("gsc-cursor")[0].style.fontSize = '20px';
};

安装回调

window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  web: {
      // Since the callback is in the global namespace, we can refer to it by name,
      // 'myWebResultsRenderedCallback', or by reference, myWebResultsRenderedCallback.
      rendered: myWebResultsRenderedCallback,
  },
};

在 HTML 中添加以下元素:

<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>
用字母表示“光标”标签

呈现的结果回调会将“游标”中的网页链接从数字更改为字母。

<script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
myWebResultsRenderedCallback = function(){
    var arr = document.getElementsByClassName('gsc-cursor-page');
    var alp = ['A','B','C','D','E','F','G','H','I','J','K','L',
      'M','N','O','p','Q','R','S','T','U','V','W','X','Y','Z'];
    for (var i = 0; i < arr.length; i++) {
        arr[i].innerHTML = alp[i];
    }
};

安装回调

window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  web: {
      // Since the callback is in the global namespace, we can refer to it by name,
      // 'myWebResultsRenderedCallback', or by reference, myWebResultsRenderedCallback.
      rendered: myWebResultsRenderedCallback,
  },
};

在 HTML 中添加以下元素:

<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

结果就绪回调示例

使用交替背景色显示结果

此回调采用交替的浅色和深色背景的格式。

<script async
      src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>

请注意:此代码是使用 JavaScript/ES6 编写的。该环境可以在大多数浏览器上运行,但对于 Internet Explorer 和其他一些旧版浏览器,需要转换为 JavaScript/ES5。

barredResultsRenderedCallback = function(gname, query, promoElts, resultElts){
  const colors = ['Gainsboro', 'FloralWhite'];
  let colorSelector = 0;
  for (const result of resultElts) {
    result.style.backgroundColor = colors[colorSelector];
    colorSelector = (colorSelector + 1) % colors.length;
  }
};
window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  web: {
    rendered: barredResultsRenderedCallback,
  },
};

在 HTML 中添加以下元素:

<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

词云

results ready 回调的明显应用是:使用 resultsRendering 回调函数调整 HTML,以一种难以到达的格式显示搜索结果。results ready 回调以空的 div 开头。Search Element API 文档中的一个示例展示了如何使用回调来呈现非常简单版本的结果。 另一个示例展示了如何保存来自 results ready 回调的结果数据,并将其传递给 resultsRendering 回调,在回调函数中可以使用这些数据来装饰标准结果显示界面。

以下 results ready 回调显示搜索结果不必是结果列表。它会将搜索结果的正常显示替换为在结果标题和内容中找到的字词的字词云。当结果列表只是用户的中间步骤时,这样的回调可以绕过该阶段,并使用结果呈现用户想要的报告。

基于搜索结果内容创建 Word Cloud
<script async
      src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
<style>
  #container {
    width: 100%;
    height: 4.5in;
    margin: 0;
    padding: 0;
  }
</style>
<script src="https://cdn.anychart.com/releases/v8/js/anychart-base.min.js"></script>
<script src="https://cdn.anychart.com/releases/v8/js/anychart-tag-cloud.min.js"></script>

请注意:此代码是使用 JavaScript/ES6 编写的。该环境可在大多数浏览器上运行,但需要转换为 JavaScript/ES5,以用于 Internet Explorer 和其他一些旧版浏览器。

const resultsReadyWordCloudCallback = function(
        name, q, promos, results, resultsDiv) {
    const stopWords = new Set()
      .add('a')
      .add('A')
      .add('an')
      .add('An')
      .add('and')
      .add('And')
      .add('the')
      .add('The');

    const words = {};
    const splitter = /["“”,\?\s\.\[\]\{\};:\-\(\)\/!@#\$%\^&*=\+\*]+/;
    if (results) {
        for (const {contentNoFormatting, titleNoFormatting} of results) {
            const wordArray = (contentNoFormatting + ' ' + titleNoFormatting)
              .split(splitter)
              .map(w => w.toLowerCase());
            for (const w of wordArray) {
                if (w && !stopWords.has(w)) {
                    words[w] = (words[w] + 1) || 1;
                }
            }
        }
    }
    const dataForChart = [];
    for (const key in words) {
        const val = words[key];
        dataForChart.push({
            'x': key,
            'value': val,
        });
    }

    const container = document.createElement('div');
    resultsDiv.appendChild(container);
    container.id = 'container';
    // create a tag (word) cloud chart
    const chart = anychart.tagCloud(dataForChart);
    // set a chart title
    chart.title(`Words for query: "${q}"`)
    // set an array of angles at which the words will be laid out
    chart.angles([0, 45, 90, 135])
    // display the word cloud chart
    chart.container(container);
    chart.draw();
    return true; // Don't display normal search results.
};
window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
    web: {
        ready: resultsReadyWordCloudCallback,
    },
};

在 HTML 中添加以下元素:

<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>

两部分回调示例

您可以结合使用 results readyresultsresults 回调,将两者中的信息从前者传递到后者。例如,结果对象数组中的信息可用于 results ready 回调,但不能由 results render 回调函数使用。 通过将这些信息作为 results ready 回调的一部分保存到数组中,我们可以让 resultsresults 回调函数访问这些信息。

例如,要绕过点击图片结果时显示的预览面板,通过两部分回调,我们可以将图片结果直接链接到相应的网站,而不是在用户点击时显示图片预览。

绕过图片预览
<script async
  src="https://cse.google.com/cse.js?cx=000888210889775888983:g9ckaktfipe"></script>
const makeTwoPartCallback = () => {
  let urls;
  const readyCallback = (name, q, promos, results, resultsDiv) => {
    urls = [];
    for (const result of results) {
      urls.push(result['contextUrl']);
    }
  };
  const renderedCallback = (name, q, promos, results) => {
    const removeEventListeners = element => {
      const clone = element.cloneNode(true);
      element.parentNode.replaceChild(clone, element);
      return clone;
    };
    for (let i = 0; i < results.length; ++i) {
      const element = removeEventListeners(results[i]);
      element.addEventListener('click', () => window.location.href = urls[i]);
    }
  };
  return {readyCallback, renderedCallback};
};
const {
  readyCallback: imageResultsReadyCallback,
  renderedCallback: imageResultsRenderedCallback,
} = makeTwoPartCallback();
window.__gcse || (window.__gcse = {});
window.__gcse.searchCallbacks = {
  image: {
    ready: imageResultsReadyCallback,
    rendered: imageResultsRenderedCallback,
  },
};

在 HTML 中添加以下元素:

<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>