Ví dụ về lệnh gọi lại khi bắt đầu tìm kiếm
Lệnh gọi lại bắt đầu tìm kiếm có thể sửa đổi cụm từ tìm kiếm trước khi được dùng cho hoạt động tìm kiếm. Bạn có thể định cấu hình Công cụ tìm kiếm có thể lập trình để đưa các cụm từ được xác định trước vào truy vấn, nhưng lệnh gọi lại này có thể sửa đổi truy vấn dựa trên mọi thông tin có sẵn cho hàm gọi lại.
Lệnh gọi lại search starting sau đây trang trí mỗi truy vấn bằng ngày hiện tại trong tuần.
<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,
},
};Thêm những phần tử này vào HTML:
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>Ví dụ này minh hoạ cách triển khai tính năng Tìm kiếm gần đây bằng lệnh gọi lại bắt đầu tìm kiếm.
Tính năng này ghi lại các cụm từ tìm kiếm của người dùng khi một lượt tìm kiếm được kích hoạt và lưu trữ các cụm từ đó cục bộ trong trình duyệt. Sau đó, những cụm từ tìm kiếm này sẽ xuất hiện dưới dạng các mục có thể nhấp, cho phép người dùng nhanh chóng lặp lại các lượt tìm kiếm trước đó, cải thiện khả năng sử dụng và giảm việc nhập liệu lặp lại.
<script async
src="https://cse.google.com/cse.js?cx=000888210889775888983:g9ckaktfipe"></script>
Xác định hàm trợ giúp để lưu trữ các cụm từ tìm kiếm gần đây trong localStorage, được bảo vệ bằng quy trình kiểm tra sự đồng ý của người dùng:
// 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);
}
}
Đăng ký lệnh gọi lại bắt đầu tìm kiếm. Bạn phải đăng ký các lệnh gọi lại trong đối tượng __gcse chung trước khi tải 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
},
},
};
Xác định một hàm để hiển thị các cụm từ tìm kiếm gần đây dưới dạng các mục có thể nhấp và khởi động hàm đó khi tải trang:
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();
});
Thêm những phần tử này vào 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>
Các điểm hạn chế
- Dữ liệu chỉ được lưu trữ trong trình duyệt (
localStorage) và yêu cầu sự đồng ý của người dùng. - Không được chia sẻ giữa các thiết bị hoặc người dùng.
- Được xoá nếu bộ nhớ của trình duyệt bị xoá.
- Không theo dõi các lượt tìm kiếm được thực hiện bên ngoài trang này.
Ví dụ về lệnh gọi lại Kết quả được hiển thị
Lệnh gọi lại kết quả được kết xuất rất phù hợp để sửa đổi trang sau khi trang được điền sẵn kết quả. Thành phần này được thiết kế để giúp bạn dễ dàng sửa đổi cách hiển thị kết quả mà không yêu cầu lệnh gọi lại chịu trách nhiệm hoàn toàn về việc hiển thị kết quả.
Các ví dụ sau đây minh hoạ 2 ứng dụng của lệnh gọi lại kết quả được kết xuất không hoạt động trên kết quả.
Lệnh gọi lại results rendered (kết quả được hiển thị) này thông báo rằng chúng ta đang hiển thị trang kết quả cuối cùng và hiển thị một cảnh báo nhắc nhở người dùng rằng họ đã đạt đến cuối.
<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");
}
};Cài đặt lệnh gọi lạ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,
},
};Thêm những phần tử này vào HTML:
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>Bản minh hoạ lệnh gọi lại kết quả được hiển thị này sẽ tăng kích thước phông chữ của các số "con trỏ" chọn trang kết quả.
Kích thước phông chữ mặc định là 12px. Ở đây, chúng ta sẽ tăng kích thước này lên 20px.
<script async
src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>myWebResultsRenderedCallback = function(){
document.getElementsByClassName("gsc-cursor")[0].style.fontSize = '20px';
};Cài đặt lệnh gọi lạ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,
},
};Thêm những phần tử này vào HTML:
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>Lệnh gọi lại results rendered này sẽ thay đổi các đường liên kết trên trang trong "con trỏ" từ số thành chữ.
<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];
}
};Cài đặt lệnh gọi lạ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,
},
};Thêm những phần tử này vào HTML:
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>Ví dụ về lệnh gọi lại Kết quả đã sẵn sàng
Lệnh gọi lại này định dạng kết quả với nền sáng và tối xen kẽ.
<script async
src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>Lưu ý: Mã này được viết bằng JavaScript/ES6. Nó sẽ chạy trên hầu hết các trình duyệt, nhưng sẽ cần được chuyển đổi sang JavaScript/ES5 cho Internet Explorer và một số trình duyệt cũ khác.
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,
},
};Thêm những phần tử này vào HTML:
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>Đám mây từ
Ứng dụng rõ ràng của lệnh gọi lại results ready là hiển thị kết quả tìm kiếm ở định dạng khó đạt được bằng lệnh gọi lại results rendered để điều chỉnh HTML. Lệnh gọi lại results ready (kết quả đã sẵn sàng) bắt đầu bằng một div trống.
Một ví dụ trong tài liệu Search Element API cho thấy cách sử dụng lệnh gọi lại để hiển thị một phiên bản kết quả rất đơn giản.
Một ví dụ khác cho thấy cách giữ dữ liệu kết quả từ lệnh gọi lại results ready và truyền dữ liệu đó đến lệnh gọi lại results rendered. Tại đây, dữ liệu có thể được dùng để trang trí màn hình kết quả tiêu chuẩn.
Lệnh gọi lại results ready (kết quả đã sẵn sàng) sau đây cho thấy rằng kết quả tìm kiếm không nhất thiết phải là một danh sách kết quả. Tiện ích này thay thế chế độ hiển thị thông thường của kết quả tìm kiếm bằng một đám mây từ gồm các từ có trong tiêu đề và nội dung của kết quả. Khi danh sách kết quả chỉ là một bước trung gian cho người dùng, một lệnh gọi lại như thế này có thể bỏ qua giai đoạn đó và sử dụng kết quả để trình bày báo cáo mà người dùng muốn.
<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>Lưu ý: Mã này được viết bằng JavaScript/ES6. Thư viện này sẽ chạy trên hầu hết các trình duyệt, nhưng cần được chuyển đổi sang JavaScript/ES5 cho Internet Explorer và một số trình duyệt cũ khác.
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,
},
};Thêm những phần tử này vào HTML:
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>Ví dụ về lệnh gọi lại gồm 2 phần
Bạn có thể kết hợp các lệnh gọi lại results ready và results rendered để truyền thông tin từ lệnh gọi trước đến lệnh gọi sau. Ví dụ: thông tin trong mảng đối tượng kết quả có sẵn cho lệnh gọi lại kết quả đã sẵn sàng, nhưng không có sẵn cho lệnh gọi lại kết quả đã hiển thị. Bằng cách lưu thông tin đó vào một mảng trong lệnh gọi lại results ready (kết quả đã sẵn sàng), chúng ta có thể truy cập vào lệnh gọi lại results rendered (kết quả đã hiển thị).
Một ví dụ về việc này là bỏ qua bảng xem trước xuất hiện khi người dùng nhấp vào một kết quả hình ảnh. Với lệnh gọi lại gồm hai phần, chúng ta có thể liên kết kết quả hình ảnh trực tiếp đến các trang web tương ứng thay vì hiển thị bản xem trước hình ảnh khi người dùng nhấp vào.
<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,
},
};Thêm những phần tử này vào HTML:
<div class="gcse-searchbox"></div>
<div class="gcse-searchresults"></div>