As you can not use the Google Custom Search
as suggested by Sergio
, you can risk the Google Web Search API
, but remember that this is deprecated
since November 2010.
In this case, you can load the API on your page, hide the element with the search, set the text to be searched and wait for the return.
In the example below, I mounted an Object carrying Google Web Search API
, he fires an event (onInitComplte
) when the Search
is available and another event (onSearchComplete
) when the consultation is complete.
In the example below, it logs into the console the sponsored link and the first link.
var Busca = function (element) {
this.container = element;
this.initialize();
}
Busca.prototype.buscar = function (texto) {
var self = this;
var click = new Event("click");
self.control.prefillQuery(texto);
//self.input.value = texto;
self.button.dispatchEvent(click);
}
Busca.prototype.initialize = function () {
var self = this;
google.load("search", "1");
google.setOnLoadCallback(function () {
var search = {};
self.control = new google.search.SearchControl();
self.control.addSearcher(new google.search.WebSearch());
self.control.addSearcher(new google.search.NewsSearch());
self.control.draw(self.container);
self.input = self.container.querySelector("input.gsc-input");
self.button = self.container.querySelector("input.gsc-search-button");
self.result = self.container.querySelector("div.gsc-results-wrapper-nooverlay");
self.control.setSearchCompleteCallback(this, function (event) {
console.log(event);
var results = {};
results.container = self.result.querySelector("div.gsc-results");
results.primeiro = {};
results.primeiro.container = results.container.querySelector("div.gsc-result");
results.primeiro.titulo = results.primeiro.container.querySelector("a.gs-title");
var expansao = {};
expansao = {};
expansao.container = results.container.querySelector("div.gsc-expansionArea");
expansao.primeiro = {};
expansao.primeiro.container = expansao.container.querySelector("div.gsc-result");
expansao.primeiro.titulo = expansao.primeiro.container.querySelector("a.gs-title");
results.expansao = expansao;
if (self.onSearchComplete) {
self.onSearchComplete(event.hf, results);
}
});
self.onInitComplete();
});
}
var container = document.getElementById("searchcontrol");
var search = new Busca(container);
search.onInitComplete = function () {
search.buscar("Hello Wolrd");
}
search.onSearchComplete = function (texto, results) {
console.log([
texto,
results.primeiro.titulo.href,
results.expansao.primeiro.titulo.href
]);
}
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<div id="searchcontrol"></div>
O Google has an API for this.
– Sergio
Hmm, I guess that doesn’t work. I’d have some other way?
– Silva97