Google site search catch search submit and trigger function

瘦欲@ 提交于 2019-11-30 22:05:58
Fayaz

Using the following CODE snippet you'll be able to capture keyboard event on enter key press in the search input field and mouse click event on the search button.

Note: This answer only captures keyboard enter & search button click events (as asked in the original question). I've added another answer that is similar, but also auto re-populates search result on every valid keystroke.

(function($, window) {
  var elementName = '';
  var initGCSEInputField = function() {
    $( '.gcse-container form.gsc-search-box input.gsc-input' )
      .on( "keyup", function( e ) {
      if( e.which == 13 ) { // 13 = enter
        var searchTerm = $.trim( this.value );
        if( searchTerm != '' ) {
          console.log( "Enter detected for search term: " + searchTerm );
          // execute your custom CODE for Keyboard Enter HERE
        }
      }
    });
    $( '.gcse-container form.gsc-search-box input.gsc-search-button' )
      .on( "click", function( e ) {
      var searchTerm = $.trim( $( '.gcse-container form.gsc-search-box input.gsc-input' ).val() );
      if( searchTerm != '' ) {
        console.log( "Search Button Click detected for search term: " + searchTerm );
        // execute your custom CODE for Search Button Click HERE
      }
    });
  };
  
  var GCSERender = function() {
  	google.search.cse.element.render({
        div: 'gcse_container',
        tag: 'search'
      });
      initGCSEInputField();
  };
  
  var GCSECallBack = function() {
    if (document.readyState == 'complete') {
      GCSERender();
    }
    else {
      google.setOnLoadCallback(function() {
        GCSERender();
      }, true );
    }
  };
  
  window.__gcse = {
  	parsetags: 'explicit',
    callback: GCSECallBack
  };
})(jQuery, window);

(function() {
  var cx = '017643444788069204610:4gvhea_mvga'; // Insert your own Custom Search engine ID here
  var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
  gcse.src = 'https://www.google.com/cse/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gcse-container" id="gcse_container">
  <gcse:search enableAutoComplete="true"></gcse:search>
</div>

The above CODE snippet uses Google Custom Search element control API.

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