How to get url of image on image click with javascript or jQuery in Google Image Search API v2? I didn't find this information in Google Search API v2 documentation. Please, help me to solve this problem.
<script>
var renderSearchElement = function() {
google.search.cse.element.render(
{
gname:'gsearch',
div: "test",
attributes: {
disableWebSearch: true,
enableHistory: true,
enableImageSearch:true,
imageSearchResultSetSize:6
},
tag: 'search'
});
var element = google.search.cse.element.getElement('gsearch');
element.execute();
};
var myCallback = function() {
if (document.readyState == 'complete') {
renderSearchElement();
}
else {
google.setOnLoadCallback(renderSearchElement, true);
}
};
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
(function() {
var cx = '000888210889775888983:tmhkkjoq81m';
var gcse = document.createElement('script');
gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
You probably want to have a listener on the image, so that when it is clicked it can report the url value. This means you need to overwrite the default cse image with your own version with listener attached.
The procedure (some code there is obsolete, but the general things work) for overwriting the default results template with your own is described here: https://developers.google.com/custom-search/docs/js/rendering
You only need to overwrite the thumbanail part, eg:
<div id="my_thumbnail">
<div data-attr="0" data-vars="{tn:(Vars.cseThumbnail && cseThumbnail.src)
? cseThumbnail : (
(Vars.thumbnail && thumbnail.src)
? thumbnail : {src:Vars.document && document.thumbnailUrl})}">
<div data-if="tn.src">
<a class="gs-image" data-attr="{href:url,target:target}" onclick="alert(this)">
<img data-if="!tn.width || !tn.height || tn.width >= tn.height * 7 / 5" class="gs-image"
data-attr="{src:tn.src}"
onload="if (this.parentNode && this.parentNode.parentNode && this.parentNode.parentNode.parentNode) {
this.parentNode.parentNode.parentNode.style.display = '';
this.parentNode.parentNode.className = 'gs-image-box gs-web-image-box gs-web-image-box-landscape';
}
"/>
<img data-elif="true" class="gs-image"
data-attr="{src:tn.src}"
onload="if (this.parentNode && this.parentNode.parentNode && this.parentNode.parentNode.parentNode) {
this.parentNode.parentNode.parentNode.style.display = '';
this.parentNode.parentNode.className = 'gs-image-box gs-web-image-box gs-web-image-box-portrait';
}
"/>
</a>
</div>
</div>
</div>
Please mind the onclick="alert(this)" part - that is the only difference I added compared with default cse template. You can change this onclick function to do something smarter with the url than just alerting it. Here's a full demo:
http://jsfiddle.net/dhkfZ/
Related
While using different styles for larger displays and mobiles, I was forced to insert two google custom search boxes in same page. The search still works perfectly but the issue is that search predictions are no longer available after inserting the second search box.
(function() {
var cx = '*****************:**********';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
The same code is using twice in the same page(especially repeated id usage) which causes the conflict I think. Already referred similar posts 'How to have multiple Google Custom Search field on the same page' and 'Multiple GCSE's on page at one time', but those are not solutions for the situation which I'm facing. How to enable both search boxes in same page work in a similar manner without causing conflict?
I'm currently experimenting with this. Getting 2 cse's with a different cx on the same page isn't that hard, but can't get the suggestions working. The v2 control api method description isn't very clear.
But with a single cx you can just do this:
html:
<div id="first"></div>
<br/>
<div id="second"></div>
js:
var renderSearchElement = function() {
google.search.cse.element.render({
div: "first",
tag: 'search'
});
google.search.cse.element.render({
div: "second",
tag: 'search'
});
};
var myCallback = function() {
if (document.readyState == 'complete') {
renderSearchElement();
} else {
google.setOnLoadCallback(renderSearchElement, true);
}
};
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
var loadElements = function() {
var cx = '*****************:**********';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
}
loadElements();
demo:
https://jsfiddle.net/501g48d4/
CSE v2 control API and render params: https://developers.google.com/custom-search/docs/element
I'm changing the search engine of my site to Google CSE.
I use "s = term" on my site and also generates urls as /search/term.html
Google can not recognize it. What must change in code?
var queryParamName = 's';
<div class="row-fluid sc-col row-dynamic-el" style="margin-bottom:40px;"><div class="row-fluid"><div id='cse' style='width: 100%;'>Loading</div></div>
<script src='//www.google.com/jsapi' type='text/javascript'></script>
<script type='text/javascript'>
google.load('search', '1', {language: 'pt', style: google.loader.themes.V2_DEFAULT});
google.setOnLoadCallback(function() {
var customSearchOptions = {};
var orderByOptions = {};
orderByOptions['keys'] = [{label: 'Relevance', key: ''} , {label: 'Date', key: 'date'}];
customSearchOptions['enableOrderBy'] = true;
customSearchOptions['orderByOptions'] = orderByOptions;
var customSearchControl = new google.search.CustomSearchControl('01111111111:111111111', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.enableSearchResultsOnly();
options.setAutoComplete(true);
customSearchControl.draw('cse', options);
function parseParamsFromUrl() {
var params = {};
var parts = window.location.search.substr(1).split('&');
for (var i = 0; i < parts.length; i++) {
var keyValuePair = parts[i].split('=');
var key = decodeURIComponent(keyValuePair[0]);
params[key] = keyValuePair[1] ?
decodeURIComponent(keyValuePair[1].replace(/\+/g, ' ')) :
keyValuePair[1];
}
return params;
}
var urlParams = parseParamsFromUrl();
var queryParamName = 's';
if (urlParams[queryParamName]) {
customSearchControl.execute(urlParams[queryParamName]);
}
}, true);
</script>
</div>
I believe you are using V1 code and not the default V2 code.
I can not comment for V1 but for V2 code, visit Look and feel section in your google cse control panel, select appropriate layout and get the code (V2). I use Results only layout and made my own custom search box. Here is how my set up work for custom query parameter:
Search box
I have custom css stylesheets for div id and class tags: searchbox2, searchcont2 and searchString2 which you need to replace with your stylesheet properties. Custom query parameter is defined under name=s in form section.
<div class="row"><div class="col-sm-12">
<div id="searchbox2" style="margin:0 auto; display: table;">
<div class="searchcont2">
<form role="search" method="get" action="https://www.example.com/search/">
<input id="searchString2" name="s" placeholder=" Search" type="text">
</form>
</div></div>
</div></div>
If you are using other search layout, i.e., two-page or two-column, you can use following for your searchbox code with data-queryParameterName will take custom search query term.
<div class="gcse-searchbox" data-resultsUrl="http://www.example.com/search/"
data-newWindow="true" data-queryParameterName="s">
For HTML5 pages, google cse requires class attribute to be set to gcse-XXX, e.g., div class="gcse-searchbox" else search results may not load as expected. See more at https://developers.google.com/custom-search/docs/element#html5
Search results
Add your google cse resultsonly code at a defined search page, e.g., https://www.example.com/search/ and replace <GOOGLE CSE CX ID> with your cse cx id. Same as searchbox, HTML5 page should have proper div class property, e.g., <div class="gcse-searchresults-only" in following case:
<div class="row"><div class="col-sm-12">
<script>
(function() {
var cx = '<GOOGLE CSE CX ID>';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<div class="gcse-searchresults-only">
</div></div>
Cheers!
I need to pass back a unique ID in place of "INSERT+ORDER+ID" for when a user clicks on our "Request Information" button to better track our visitors. Does anyone know how I can accomplish this? Any help would be much appreciated, thanks!
<script type="text/javascript">
var _qevents = _qevents || [];
(function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") +
".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scpt = document.getElementsByTagName('script')[0];
scpt.parentNode.insertBefore(elem, scpt);
})();
_qevents.push(
{qacct:"p-yeADJca0S9FXE",labels:"_fp.event.Request Information Confirmation
Page",orderid:"INSERT+ORDER+ID"}
);
</script>
<noscript>
<img src="//pixel.quantserve.com/pixel
/p-yeADJca0S9FXE.gif?labels=_fp.event.Request+Information+Confirmation+Page&
orderid=INSERT+ORDER+ID" style="display: none;" border="0" height="1" width="1" alt="Quantcast"/>
</noscript>
assuming you mean a random unique ID,
for the javascript event tracking this should work:
// function to generate random id in js
function getRandomId() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
var btnReqInfo = document.getElementById('request_information_btn');
// bind the click on button
btnReqInfo.addEventListener('click', function() {
// track the event
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage",orderid: getRandomId() });
, false);
About the content in the noscript tag, you can't do it with static html of course so you have to put in the context of your template (in the php file), something like this that generates a unique ID and then echo it in place of your placeholder.
Since I'm in the mood for structuring and cleaning, I took the liberty of refactoring a bit the code, in case, you can replace all your script with this (assuming you're using plain js (vanilla) and html 5):
<script>
var _qevents = _qevents || [];
(function() {
var
init = function() {
loadScript();
bindUi();
},
loadScript = function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scrpt = document.getElementsByTagName('script')[0];
scrpt.parentNode.insertBefore(elem, scrpt);
},
bindUi = function() {
var btnReqInfo = document.getElementById('request_information_btn');
btnReqInfo.addEventListener('click', track.order, false);
},
track = {
order: function() {
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage", orderid: utils.getRandomId() });
}
},
utils = {
getRandomId : function() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
};
init();
})();
</script>
I would suggest using an AJAX call that is binded to the onclick event or .click if you're using JQuery
The AJAX call would hit a PHP script or call whatever you're using for analytics.
Setting up Google Custom Search: https://www.google.com/cse/
I would like to be able to use JS to call the search terms the users are keying.
<script>
(function () {
var cx = 'mygoogle-gcse-id';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();</script>
How do I use JS to call the elements entered into the search form?
I would want to call:
onblur="somefunction('gsce-input-data')";
The search elements are created on the fly when the code above loads the script. This means you need to attach your listeners using the "live" method, so that they get attached when the element actually enters the DOM:
$('.gsc-input').live('blur', function(e) { //do something });
Here is the fiddle example: http://jsfiddle.net/pASWm/1/
I have a Google Custom Search (that will be a Site Search in the future) and I'd like to use the snippet that Google provides:
<script>
(function() {
var cx = '...';
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:search></gcse:search>
I need to restrict it to certain urls. When using the xml api, you can use the parameter as_sitesearch to specify this filter.. is there a way to do this with the code above?
with this I can now access the google.search.cse object before the search is loaded.. but I still don't know parameter:
<script>
var myCallback = function() {
if (document.readyState == 'complete') {
// Document is ready when CSE element is initialized.
// Render an element with both search box and search results in div with id 'test'.
google.search.cse.element.render(
{
div: "test",
tag: 'search'
});
} else {
// Document is not ready yet, when CSE element is initialized.
google.setOnLoadCallback(function() {
// Render an element with both search box and search results in div with id 'test'.
google.search.cse.element.render(
{
div: "test",
tag: 'search'
});
}, true);
}
};
// Insert it before the CSE code snippet so that cse.js can take the script
// parameters, like parsetags, callbacks.
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
(function() {
var cx = '007407192365638902354:eyxoavi7oa0';
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>
<style>
.gsc-control-cse * {
box-sizing:content-box;
}
</style>
Yes you can.
Use a hidden field inside your search form:
<input type="hidden" name="as_sitesearch" value="your_url_here/directory">
I've got the same question. The only way I have been able to restrict the search to a particular folder in Google Site Search version 2 is to hard-code it into the element:
<gcse:search as_sitesearch="www.mydomain.com/site1"></gcse:search>
It would be great if there was a way to add as_sitesearch via JavaScript, like with version 1.
To restrict to certain urls:
<gcse:searchbox-only as_sitesearch="mydomain.com" resultsUrl="http://mydomain.com/search-results/" enableAutoComplete="false"></gcse:searchbox-only>
Be sure to replace mydomain.com with the appropriate domain that you want to restrict to.