검색 시작 콜백 예
검색 시작 콜백은 검색에 사용되기 전에 쿼리를 수정할 수 있습니다. 프로그래밍 검색 엔진은 사전에 결정된 검색어를 검색어에 포함하도록 구성할 수 있지만 이 콜백은 콜백에 사용 가능한 모든 정보를 기반으로 쿼리를 수정할 수 있습니다. 함수를 사용하세요.
다음 검색 시작 콜백은 각 쿼리를 오늘 날짜로 장식합니다. 입니다.
<ph type="x-smartling-placeholder"><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>
결과 렌더링 콜백 예시
결과 렌더링 콜백은 결과가 채워진 후 페이지를 수정하는 데 유용합니다. 콜백 없이도 결과 표시를 쉽게 수정할 수 있도록 설계되었습니다. 결과 렌더링에 대한 전적인 책임을 질 수 있습니다
다음 예는 결과에 대해 연산을 수행하지 않습니다
<ph type="x-smartling-placeholder">이 결과 렌더링 콜백은 마지막 페이지가 표시되었음을 알립니다. 사용자에게 마지막에 도달했음을 알려주는 알림을 표시합니다.
<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>
이 결과 렌더링 콜백 데모는 "cursor" 숫자입니다.
기본 글꼴 크기는 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>
이 렌더링된 결과 콜백은 '커서'의 페이지 링크를 변경합니다. 할 수 있습니다.
<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>
결과 준비 콜백 예시
<ph type="x-smartling-placeholder">이 콜백 형식을 사용하면 밝은 배경과 어두운 배경이 번갈아 표시됩니다.
<script async
src="https://cse.google.com/cse.js?cx=000888210889775888983:y9tkcjel090"></script>
참고: 이 코드는 JavaScript/ES6로 작성됩니다. 대부분의 브라우저에서 실행되지만 Internet Explorer 및 기타 이전 버전에서 사용할 수 있도록 있습니다.
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 렌더링된 결과 콜백을 사용하여
HTML을 선택합니다. 결과 준비 완료 콜백은 빈 div
로 시작합니다.
Search Element API 문서에 있는 한 가지 예
콜백을 사용하여 매우 간단한 버전의 결과를 렌더링하는 방법을 보여주었습니다.
또 다른 예
는 results ready 콜백의 결과 데이터를 보유하고 이 데이터를
표준 결과를 데코레이션하는 데 사용할 수 있는 results 렌더링 콜백
디스플레이.
다음 결과 준비됨 콜백은 검색 결과에 결과 목록입니다. 일반 검색 결과 표시를 대체합니다. 단어 구름을 바꾸어 볼 수 있습니다. 생성할 수 있습니다. 목록에서 결과는 사용자의 중간 단계일 뿐이며, 이와 같은 콜백은 해당 단계를 우회할 수 있습니다. 결과를 사용하여 사용자가 원하는 보고서를 제시할 수 있습니다.
<ph type="x-smartling-placeholder"><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로 작성됩니다. 대부분의 브라우저에서 실행되지만 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>
두 부분으로 구성된 콜백 예시
결과 준비 완료 및 결과 렌더링 콜백을 함께 사용하여 전자에서 후자로 정보를 전달할 수 있습니다. 예를 들어 결과 객체 배열의 정보는 결과 준비됨 콜백에서 사용할 수 있지만 결과 렌더링됨 콜백에서는 사용할 수 없습니다. 이 정보를 결과 준비됨 콜백의 일부로 배열에 저장하여 결과 렌더링됨 콜백이 해당 정보에 액세스하도록 할 수 있습니다.
한 가지 예는 이미지 검색결과를 클릭할 때 표시되는 미리보기 패널을 우회하는 것입니다. 두 부분으로 구성된 콜백을 사용하면 이미지를 클릭할 때 이미지 미리보기를 표시하는 대신 해당 웹사이트로 바로 연결되는 이미지 결과 링크를 만들 수 있습니다.
<ph type="x-smartling-placeholder"><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>