Google CSE - search parameter - javascript

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!

Related

I am using TypeForm and need to autofill hidden fields from a .js script

I am using TypeForm and need to autofill utm fields from javascript, everything works except I cant get the html created from the script to show on the page. I am embedding the below code in a html/js module in a clickfunnels page. Any help is very much appreciated.
<div id="typeform"></div>
<script>
//<div id="typeform"></div> <div id="row--27712"></div>
window.onload = function(){
var source = "utm_source=1";
var medium = "utm_medium=2";
var campaign = "utm_campaign=3";
var content = "utm_content=4";
var keyword = "utm_term=5"
var HTMLA = '<div data-tf-widget="mYH43Dz4" data-tf-iframe-props="title=TFS - ANALYTICSDEV V1.1" data-tf-medium="snippet" data-tf-hidden=';
var HTMLquote = '"';
var HTMLcomma = ',';
var HTMLB = '" style="width:100%;height:600px;"></div><script src="//embed.typeform.com/next/embed.js">';
var HTMLC = '</'
var HTMLD = 'script>'
var form = HTMLA.concat(HTMLquote).concat(source).concat(HTMLcomma).concat(medium).concat(HTMLcomma).concat(campaign).concat(HTMLcomma).concat(content).concat(HTMLcomma).concat(keyword).concat(HTMLB);
var form2 = form.replaceAll("undefined","");
document.getEIementById('typeform').innerHTML = form2;
};
</script>
You can pass custom values to hidden fields like this:
<div id="typeform"></div>
<link rel="stylesheet" href="//embed.typeform.com/next/css/widget.css" />
<script src="//embed.typeform.com/next/embed.js"></script>
<script>
var source = '1';
var medium = '2';
var campaign = '3';
var content = '4';
var keyword = '5';
window.tf.createWidget('mYH43Dz4', {
container: document.getElementById('typeform'),
hidden: {
utm_source: source,
utm_medium: medium,
utm_campaign: campaign,
utm_content: content,
utm_term: keyword
}
});
</script>
In case you already have those values in your host page URL, you could use transitive search params feature:
<div
data-tf-widget="mYH43Dz4"
data-tf-transitive-search-params="utm_source,utm_medium,utm_campaign,utm_content,utm_term"
></div>
<script src="//embed.typeform.com/next/embed.js"></script>
Your code does not work because you are adding script tag via innerHTML. This script tag will not execute for security purposes:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0

Two custom searches in same page disables search predictions

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

How to pass back a unique ID with JavaScript or PHP?

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.

How to get image url in google image search api v2

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/

How can I specify as_sitesearch in v2 of Google Site Search / Custom Search?

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.

Categories