最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use Google Custom Search Element with existing form element? - Stack Overflow

programmeradmin2浏览0评论

I'm trying to use my current search form with Google's custom search element and so far I am unable to get it to work. This is my current search form.

<form class="search-form" action="/search/">
    <p class="inputs">
        <label for="search-q">Search</label>
        <input type="search" id="search-q" name="search" data-gname="search"placeholder="Find what you're looking for..." value="#formatted_query#">
        <input type="submit" value="Go" class="button postfix brand-orange-bk">
    </p>
</form>

The Google CSE code snippet I use is shown below:

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];

    s.parentNode.insertBefore(gcse, s);

  })();
  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

In the result (which is on the same page), I have the following:

<div class="row">
    <div class="small-12 medium-5 medium-push-7 large-5 large-push-7 columns" id="search-rightcol">
        <section data-searchtab="our-own-knowledgebase" class="search-panel brand-white-bk"></section>
    </div>
    <div class="small-12 medium-7 medium-pull-5 large-7 large-pull-5 columns">
        <div id="google-search-results"></div>
    </div>
</div>

I can use the gcse:searchbox-only tag instead of my current form and then I'll style it; however, when I press the search button, it goes to a different page and the result is not display in the google-search-results div. If I use the gcse:search tag then the result replaces everything on the current page and disregard this line of code:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

I have looked at the HTML5-valid div tags, Custom Search Element Control API (V2), and Using the JavaScript API to render elements but I'm unclear as to how I would go about modifying the code in my situation so I can simply pass whatever value is in the input element to the Google CSE code to do the search and then I'll put the result in the google-search-results div. In the example of the Custom Search Element Control API (V2), it showed this code:

var element = google.search.cse.element.getElement('element1);
element.execute('news');

So I tried the following code but it didn't work...no result is showing/returning.

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = '.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google/cse.js?cx=' + cx;
    //var s = document.getElementsByTagName('script')[0];
    var s = google.search.cse.element.getElement('search');

    // do the search:
    var searchTerm = $('##search-q').val();
    s.execute(searchTerm);

    s.parentNode.insertBefore(gcse, s);

  })();

  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

I have found a similar thread (How to use custom search box for google custom search?) but there is no resolution to that thread. I have also found another thread (How to style Google Custom Search Engine so that it doesn't display as a block element) but the problem I have with that solution is whenever I clicked to search, it would go to a different page disregard this code:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

Any help is much appreciated. Thank you.

I'm trying to use my current search form with Google's custom search element and so far I am unable to get it to work. This is my current search form.

<form class="search-form" action="/search/">
    <p class="inputs">
        <label for="search-q">Search</label>
        <input type="search" id="search-q" name="search" data-gname="search"placeholder="Find what you're looking for..." value="#formatted_query#">
        <input type="submit" value="Go" class="button postfix brand-orange-bk">
    </p>
</form>

The Google CSE code snippet I use is shown below:

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google./cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];

    s.parentNode.insertBefore(gcse, s);

  })();
  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

In the result (which is on the same page), I have the following:

<div class="row">
    <div class="small-12 medium-5 medium-push-7 large-5 large-push-7 columns" id="search-rightcol">
        <section data-searchtab="our-own-knowledgebase" class="search-panel brand-white-bk"></section>
    </div>
    <div class="small-12 medium-7 medium-pull-5 large-7 large-pull-5 columns">
        <div id="google-search-results"></div>
    </div>
</div>

I can use the gcse:searchbox-only tag instead of my current form and then I'll style it; however, when I press the search button, it goes to a different page and the result is not display in the google-search-results div. If I use the gcse:search tag then the result replaces everything on the current page and disregard this line of code:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

I have looked at the HTML5-valid div tags, Custom Search Element Control API (V2), and Using the JavaScript API to render elements but I'm unclear as to how I would go about modifying the code in my situation so I can simply pass whatever value is in the input element to the Google CSE code to do the search and then I'll put the result in the google-search-results div. In the example of the Custom Search Element Control API (V2), it showed this code:

var element = google.search.cse.element.getElement('element1);
element.execute('news');

So I tried the following code but it didn't work...no result is showing/returning.

(function() {
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google./cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google./cse.js?cx=' + cx;
    //var s = document.getElementsByTagName('script')[0];
    var s = google.search.cse.element.getElement('search');

    // do the search:
    var searchTerm = $('##search-q').val();
    s.execute(searchTerm);

    s.parentNode.insertBefore(gcse, s);

  })();

  $('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

I have found a similar thread (How to use custom search box for google custom search?) but there is no resolution to that thread. I have also found another thread (How to style Google Custom Search Engine so that it doesn't display as a block element) but the problem I have with that solution is whenever I clicked to search, it would go to a different page disregard this code:

$('##google-search-results').html('<gcse:searchresults-only></searchresults-only>');

Any help is much appreciated. Thank you.

Share Improve this question edited May 23, 2017 at 12:32 CommunityBot 11 silver badge asked Mar 28, 2017 at 14:15 2myCharlie2myCharlie 1,9475 gold badges26 silver badges40 bronze badges 2
  • Never used gcse but are you supposed to have 2 hashtags in the jquery identifier? I could be wrong here just asking. – bryangators55 Commented Mar 28, 2017 at 14:30
  • That's a ColdFusion thing. I got confused the first time I used it too. – 2myCharlie Commented Mar 28, 2017 at 14:44
Add a ment  | 

2 Answers 2

Reset to default 2

Okay, thanks to colleagues of mine, this is how we resolved it. I'm putting it here perhaps it might help others.

searchhelper.perform_google = function(){

    if(typeof(google)!='undefined'){
        google.search.cse.element.render({
            div: "google-search-results",
            tag: 'searchresults-only',
            gname: 'google-results-gname'
        });
        var element = google.search.cse.element.getElement('google-results-gname');
        var query = $('##search-q').val();
        element.execute(query);
    }
};

(function(){
    // add the google custom stuff:
    var cx = '004626212387516433456:aex2tyveipy';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    //gcse.src = 'https://cse.google./cse.js?cx=' + cx;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google./cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})();

window.__gcse = {
  parsetags: 'explicit',
  callback: function(){
    searchhelper.search('all');
  }
};

Already had this scenario before and after a lot of investigation and searching found the below: Here is a plete example of how to do this, you just need to update it with your own CSE ID And you Domain and section you might need to use while filtering the returning result.

<!DOCTYPE html>
<html>
<head>
<title>CSE V2: Custom Search Engine Programarically</title>
<style type="text/css">
h4.warning {color: red;}
h4.remendation {color: green;}
.gs-image-box , .gs-web-image-box {
  display:none ; 
}
  .gcsc-branding , .gsc-above-wrapper-area {
    display:none ; 
  }
</style>

<!-- Put the following javascript before the closing </head> tag. -->
<script type="text/javascript">
  var searchQuery = "";
  var renderSearchTextboxElement = function() {
    google.search.cse.element.render(
      {
        div: "dynamicTXT1",
		tag: 'searchbox-only',
		gname: 'main-search-button1',
		 attributes: {
          enableAutoComplete: true,
          enableHistory: true,
		  resultsUrl: '/search',
		  queryParameterName: 'q'

		  }
      });
    google.search.cse.element.render(
      {
        div: "dynamicTXT2",
		tag: 'searchbox-only',
		gname: 'main-search-button2',
		 attributes: {
          enableAutoComplete: true,
          enableHistory: true,
		  resultsUrl: '/search',
		  queryParameterName: 'q'

		  }
      });
  }
    var renderSearchElement = function(restructedTo) {
    var as_sitesearchVal = ""; 
    var filtersItems = restructedTo.split(' ');
    if(filtersItems.length == 1){
      as_sitesearchVal = restructedTo;
    }
    var resultlist = google.search.cse.element.getElement('main-searchresults');
    if(resultlist){
      resultlist.clearAllResults();
      document.getElementById("default").innerHTML = "";
    }
    google.search.cse.element.render(
      {
        div: "default",
        tag: 'searchresults-only',
        gname: 'main-searchresults',
        attributes: {
		  queryParameterName: 'q',
          as_oq:restructedTo,
          as_sitesearch:as_sitesearchVal,
		  },
      });
     };
  
  var i = 0
  function executeQuery(filterName) {
    // set textboxes values based on the querystring
    if(searchQuery){
      google.search.cse.element.getElement('main-search-button1').prefillQuery(searchQuery);
      google.search.cse.element.getElement('main-search-button2').prefillQuery(searchQuery);
    }
     console.log(filterName);
     renderSearchElement(filterName);
    console.log(i++);
    if (typeof google != 'undefined' ){
      
      if(!searchQuery){
         if(google.search.cse.element.getElement('main-search-button1').getInputQuery()){
           searchQuery = google.search.cse.element.getElement('main-search-button1').getInputQuery();
         }else if(google.search.cse.element.getElement('main-search-button2').getInputQuery()){
           searchQuery = google.search.cse.element.getElement('main-search-button2').getInputQuery();
         }
      }
      var input = document.getElementById('cse-search-input-box-id');
      var element = google.search.cse.element.getElement('main-searchresults');
      if (searchQuery == '') {
        element.clearAllResults();
      } else {
        element.execute(searchQuery);
      }
      return false;
    }else{
      setTimeout(executeQuery,500);
    }
  }
//  setTimeout(executeQuery,1000);
  
  //document.forms["myform"].submit();
</script>
  <script>
    var myCallback = function() {
    if (document.readyState == 'plete') {
      searchQuery = getParameterByName('q',window.location.href);
      renderSearchTextboxElement();
      executeQuery("");
     
    } else {
      google.setOnLoadCallback(function() {
        renderSearchTextboxElement();
        executeQuery("");
      }, true);
    }
  };
    
 window.__gcse = {
  callback: myCallback
};
  
  (function() {
    var cx = '123:456'; // Insert your own Custom Search engine ID here
    var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = false;
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
        '//www.google./cse/cse.js?cx=' + cx;
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
  })();
    
     function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>
</head>

<body>
<!-- Search box form -->
  <a href="#" class="" onclick="executeQuery('');" data-filter="people">All</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain./section1');" data-filter="section1">section1</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain./section2');" data-filter="section2">section2</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain./section3 subdomain.your-domain. ~/your-domain');" data-filter="section3">section3</a>
  <div></div>
  <a href="#" class="" onclick="executeQuery('www.your-domain./section4');" data-filter="section4">section4</a>
  
  <div id="dynamicTXT1"></div>
  <div id="dynamicTXT2"></div>
  <div id="default"></div>
<form style="display:none" onsubmit="return executeQuery(false);" id="cse-search-box-form-id">
  <!-- This is the input searc box -->
  <input type="text" id="cse-search-input-box-id" data-as_oq="/section1" autoplete="off" value="energy"/>
  <!-- This is the search button -->
  <input type="submit" value="Search"/>
</form>

<script type="text/javascript"
        src="//www.google./cse/brand?form=cse-search-box-form-id&inputbox=cse-search-input-box-id">
</script>
<!-- End of Google branding watermark -->

<!-- Element code snippet -->


<!-- Place this tag where you want the search results to render -->
<hr >
<!-- <gcse:searchresults-only enableOrderBy="false"></gcse:searchresults-only> -->
</body>

</html>

发布评论

评论列表(0)

  1. 暂无评论