Search code examples
javascripthtmlsearch-enginegoogle-search

How to add custom Google search to my customized search box?


So I want to keep the styling of my own Google box, but I want to direct to Google Search of my page.

The code looks something like this:

<......>
</ul>
<form action="" method="post" id="FORM_10">
  <div id="DIV_11">
    <link href="css/search.css" rel="stylesheet" type="text/css"  id="LINK_12">

    <div id="DIV_14">
        <div id="DIV_15">
          <div id="DIV_16">
            <div id="DIV_17">
              <div id="DIV_18">
                <div id="DIV_19">
                  <div id="DIV_20">
                    <div id="DIV_21">
                      <input value="sdasdsad" id="INPUT_22" name="keys" size="60" maxlength="255" type="text">
                    </div>

                  </div>
                  <input id="INPUT_44" name="op" value="search" type="submit">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
  </div>
   </form> <a href="#" id="A_45" title="english">en</a> <a href="#" id="A_46" title="contacts">contacts</a>
    </div>       

and I would like to somehow add the functionality as if gcse:search is present in my code, but I want to remain with my own stylized search box, but when the users inserts his string to the search box, he gets a pop-up overlay window with Google search results on specified site.

Worst case scenario. I would like to find out how can I properly customize the Google search box.


Solution

  • Google has support for "custom" search engines which you can register here, which allows you to specify domains (and paths) that you want to include in the search (the equivalent of a site: parameter in a search):

    Google CSE

    Now, for this example, I made a search for https://developer.mozilla.org, since their insite search isn't as good as google's. I labeled it MDN, and clicked create (after agreeing to the terms of service):

    Create the search engine for mozilla

    From here we'll get the source code to use with the Get Code button, which will give us an HTML snippet to insert. Mine looked like this:

    <script>
      (function() {
        var cx = '005381150112327209486:iwm6p6iff_4';
        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:search></gcse:search>
    

    Insert the script into your <head> and place the <gcse:search> tag where you want the input to appear. Read about custom styling of these here

    Hope this was helpful!