ตัวอย่างโค้ดเรียกกลับขององค์ประกอบการค้นหาเพิ่มเติม

หน้านี้มีตัวอย่างการใช้การเรียกกลับของ Search Element ที่หลากหลาย ซึ่งจะช่วยเสริมตัวอย่างที่อยู่ในส่วนการเรียกกลับของเอกสาร Custom Search Element API

ตัวอย่างการเรียกกลับเมื่อเริ่มการค้นหา

Callback search starting สามารถแก้ไขคําค้นหาก่อนที่จะใช้สําหรับการค้นหาได้ คุณกำหนดค่า Programmable Search Engine ให้รวมคำที่กำหนดไว้ล่วงหน้าไว้ในคำค้นหาได้ แต่ การเรียกกลับนี้จะแก้ไขคำค้นหาตามข้อมูลใดก็ตามที่ฟังก์ชันการเรียกกลับ มีอยู่ได้

การเรียกกลับ search starting ต่อไปนี้จะตกแต่งการค้นหาแต่ละครั้งด้วยวัน ในสัปดาห์ปัจจุบัน

ตัวอย่างการเรียกกลับเมื่อเริ่มการค้นหา
<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>
การแสดงลิงก์ "การค้นหาล่าสุด"

ตัวอย่างนี้แสดงวิธีใช้ฟีเจอร์การค้นหาล่าสุดโดยใช้ Callback search starting

ฟีเจอร์นี้จะบันทึกคำค้นหาของผู้ใช้เมื่อมีการทริกเกอร์การค้นหา และจัดเก็บไว้ในเบราว์เซอร์ในเครื่อง จากนั้นระบบจะแสดงคำค้นหาเหล่านี้เป็นรายการที่คลิกได้ ซึ่งช่วยให้ผู้ใช้ทำซ้ำการค้นหาก่อนหน้าได้อย่างรวดเร็ว จึงปรับปรุงความสามารถในการใช้งานและลดการพิมพ์ซ้ำ

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

กำหนดฟังก์ชันตัวช่วยเพื่อจัดเก็บการค้นหาล่าสุดใน localStorage โดยมี การตรวจสอบความยินยอมของผู้ใช้เป็นตัวควบคุม

      // For this demo, consent is assumed to be granted.
        // In production, integrate this with your site's Consent Management Platform (CMP).
        window.__hasStorageConsent = true;

        function hasStorageConsent() {
          return window.__hasStorageConsent === true;
        }

        function saveRecentSearch(query) {
          if (!query || !hasStorageConsent()) return;

          let searches = [];
          try {
            searches = JSON.parse(localStorage.getItem("recentSearches")) || [];
          } catch (e) {
            console.warn("Invalid localStorage data, resetting:", e);
            // searches remains [] to overwrite the corrupted data
          }

          searches = searches.filter(item => item !== query);
          searches.unshift(query);
          searches = searches.slice(0, 5);

          try {
            localStorage.setItem("recentSearches", JSON.stringify(searches));
          } catch (e) {
            console.warn("Unable to access localStorage:", e);
          }
        }
      
    

ลงทะเบียนการเรียกกลับการค้นหาเริ่มต้น ต้องลงทะเบียนการเรียกกลับในออบเจ็กต์ส่วนกลาง __gcse ก่อนโหลด cse.js

      // Install the callback.
        window.__gcse || (window.__gcse = {});
        window.__gcse.searchCallbacks = {
          web: {
            starting: function (gname, query) {
              saveRecentSearch(query);
              renderRecentSearches();
              return query; // continue normal search
            },
          },
        };
      
    

กำหนดฟังก์ชันเพื่อแสดงการค้นหาล่าสุดเป็นรายการที่คลิกได้และเริ่มต้นฟังก์ชันเมื่อโหลดหน้าเว็บ

      function renderRecentSearches() {
        const container = document.getElementById("recent-searches");
        if (!container) return;
        if (!hasStorageConsent()) {
          container.innerHTML = "";
          try {
            localStorage.removeItem("recentSearches");
          } catch(e) {}
          return;
        }
        let searches = [];
        try {
          searches = JSON.parse(localStorage.getItem("recentSearches")) || [];
        } catch (e) {
          console.warn("Unable to access localStorage:", e);
        }
        container.innerHTML = "";
        searches.forEach(q => {
          const item = document.createElement("button");
          item.type = "button";
          item.textContent = q;
          item.onclick = () => {
            const input = document.querySelector("input.gsc-input");
            const button = document.querySelector("button.gsc-search-button");
            if (input) input.value = q;
            if (button) button.click();
          };
          container.appendChild(item);
        });
      }

      window.addEventListener("DOMContentLoaded", function () {
        renderRecentSearches();
      });
      
    

รวมองค์ประกอบต่อไปนี้ไว้ใน HTML

      
        <style>
          #recent-searches button {
            display: inline-block;
            margin-right: 8px;
            margin-top: 4px;
            padding: 2px 8px;
            background-color: #f1f3f4;
            border: 1px solid #dadce0;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
          }
        </style>
        <div class="gcse-search"></div>
        <div id="recent-searches"></div>
      
    

ข้อจำกัด

  • ระบบจะจัดเก็บข้อมูลไว้ในเบราว์เซอร์เท่านั้น (localStorage) และต้องได้รับความยินยอมของผู้ใช้
  • ไม่แชร์ในอุปกรณ์หรือผู้ใช้
  • ล้างออกหากมีการล้างพื้นที่เก็บข้อมูลของเบราว์เซอร์
  • ไม่ติดตามการค้นหาที่ทำนอกหน้านี้

ตัวอย่าง Callback ที่แสดงผล

การเรียกกลับของผลลัพธ์ที่แสดงผลเหมาะสำหรับการแก้ไขหน้าเว็บหลังจากที่แสดงผลลัพธ์แล้ว โดยออกแบบมาเพื่อให้แก้ไขการแสดงผลลัพธ์ได้ง่ายโดยไม่ต้องให้ฟังก์ชันเรียกกลับ รับผิดชอบในการแสดงผลลัพธ์ทั้งหมด

ตัวอย่างต่อไปนี้แสดงการใช้งาน 2 อย่างของโค้ดเรียกกลับที่แสดงผล ซึ่ง ไม่ได้ดำเนินการกับผลลัพธ์

ระบุหน้าผลการค้นหาสุดท้าย

การเรียกกลับแสดงผลลัพธ์นี้จะแจ้งให้ทราบว่าเรากำลังแสดงผลลัพธ์หน้าสุดท้าย และจะแสดงการแจ้งเตือนเพื่อเตือนผู้ใช้ว่าได้เลื่อนมาถึงจุดสิ้นสุดแล้ว

<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>
การเพิ่มขนาดแบบอักษรของลิงก์ "เคอร์เซอร์"

การสาธิตการเรียกกลับ results rendered นี้จะเพิ่มขนาดแบบอักษรของตัวเลข "เคอร์เซอร์" ที่เลือกหน้าผลการค้นหา

ขนาดแบบอักษรเริ่มต้นคือ 12 พิกเซล ในที่นี้ เราจะเพิ่มเป็น 20 พิกเซล

<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>
ใช้ตัวอักษรสำหรับป้ายกำกับ "เคอร์เซอร์"

การเรียกกลับ results rendered นี้จะเปลี่ยนลิงก์หน้าใน "เคอร์เซอร์" จากตัวเลขเป็นตัวอักษร

<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 &lt 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 โดยจะทำงานในเบราว์เซอร์ส่วนใหญ่ แต่จะต้องแปลงเป็น JavaScript/ES5 สำหรับ Internet Explorer และเบราว์เซอร์รุ่นเก่าอื่นๆ อีก 2-3 รายการ

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>

Word Cloud

การใช้งาน Callback results ready ที่ชัดเจนคือการแสดงผลการค้นหาใน รูปแบบที่เข้าถึงได้ยากโดยใช้ Callback results rendered เพื่อปรับแต่ง HTML การเรียกกลับ results ready จะเริ่มต้นด้วย div ที่ว่างเปล่า ตัวอย่างหนึ่งในเอกสาร Search Element API แสดงวิธีใช้ Callback เพื่อแสดงผลเวอร์ชันผลการค้นหาที่เรียบง่ายมาก อีกตัวอย่างหนึ่ง แสดงวิธีเก็บข้อมูลผลลัพธ์จากแฮนเดิล results ready และส่งไปยัง แฮนเดิล results rendered ซึ่งใช้เพื่อตกแต่งการแสดงผลลัพธ์มาตรฐานได้

การเรียกกลับ results ready ต่อไปนี้แสดงให้เห็นว่าผลการค้นหาไม่จำเป็นต้อง เป็นรายการผลการค้นหา โดยจะแทนที่การแสดงผลการค้นหาตามปกติ ด้วยเวิร์ดคลาวด์ของคำที่พบในชื่อและเนื้อหาของผลการค้นหา เมื่อรายการผลลัพธ์เป็นเพียงขั้นตอนกลางสำหรับผู้ใช้ การเรียกกลับเช่นนี้จะข้ามขั้นตอนนั้น และใช้ผลลัพธ์เพื่อแสดงรายงานที่ผู้ใช้ต้องการได้

สร้างภาพกลุ่มคำจากเนื้อหาผลการค้นหา
<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 และเบราว์เซอร์รุ่นเก่าอื่นๆ อีก 2-3 รายการ

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>

ตัวอย่าง Callback แบบ 2 ส่วน

คุณสามารถใช้แฮนเดิล results ready และ results rendered ร่วมกันเพื่อส่งข้อมูลจากแฮนเดิลแรกไปยังแฮนเดิลที่สอง ตัวอย่างเช่น ข้อมูลในอาร์เรย์ของออบเจ็กต์ผลลัพธ์จะพร้อมใช้งานในโค้ดเรียกกลับ results ready แต่ไม่ใช่โค้ดเรียกกลับ results rendered การบันทึกข้อมูลดังกล่าวลงในอาร์เรย์เป็นส่วนหนึ่งของโค้ดเรียกกลับ results ready จะช่วยให้เราเข้าถึงโค้ดเรียกกลับ results rendered ได้

ตัวอย่างหนึ่งของการดำเนินการนี้คือการข้ามแผงแสดงตัวอย่างที่แสดงเมื่อคลิกผลการค้นหารูปภาพ การเรียกกลับแบบ 2 ส่วนช่วยให้ผลการค้นหารูปภาพลิงก์ไปยังเว็บไซต์ที่เกี่ยวข้องได้โดยตรงแทนที่จะแสดงตัวอย่างรูปภาพเมื่อคลิก

ข้ามตัวอย่างรูปภาพ
<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>