Multiple GCSE's on page at one time.

霸气de小男生 提交于 2019-12-02 07:33:25

With Custom Search Element v1 it can be done relatively easy:

<script src='//www.google.com/jsapi' type='text/javascript'></script>
<script type='text/javascript'>
google.load('search', '1', {style: google.loader.themes.V2_DEFAULT});
google.setOnLoadCallback(function () {
  new google.search.CustomSearchControl('CSE_USER_ID:CDE_ID1').draw('cse');
  new google.search.CustomSearchControl('CSE_USER_ID:CDE_ID2').draw('cse2');
});
</script>

<div id='cse' style="width: 100%;">Loading</div>

<div id='cse2' style="width: 100%;">Loading</div>

Demo: Multiple Google CSE on the same page
http://box.galeksic.com/cse.multiple-on-same-page/

JavaScript API Reference (v1)
https://developers.google.com/custom-search/docs/js/cselement-reference

I've tried with v2, but wasn't very successful.

I was struggling with this same problem and came across this post on the google product forums.

Basically, the answer is to use a single CSE and differentiate what you're searching using refinements, which allow you to scope the searched URLs using labels in your CSE settings.

Note: make sure to set the refinement to 'search only sites with this label' assuming that's what you want.

Then, in your HTML code, specify the default refinement you want to use for each results box like so:

<script>
  (function() {
  var cx = 'your-cse-id-here';
  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);
  })();
</script>

<gcse:searchresults-only defaultToRefinement="refinement-tag-1"></gcse:searchresults-only>

<gcse:searchresults-only defaultToRefinement="refinement-tag-2"></gcse:searchresults-only>

For my use, I wanted to not display the default refinement tabs (and have the two result boxes look like they were independent) so I used CSS to hide the 'gsc-tabsArea' elements.

More info on v2 CSE API and refinements...

Here's a working codepen: http://codepen.io/mikedaul/pen/xqxYOO?q=flowers

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!