スタートページJavascript Google Search

Custom Search Element Control API (V2)の実例

Custom Search Element Control API は、Custom Search Elementsの各種パラメタをJavascriptで指定するためのAPIです。

これをWebページに組み込むには、事前にGoogleサイトで「カスタム検索エンジンID」を取得し、対象とするWebサイトを設定しておく必要があります。

参照:Google「Custom Search Element V2」
   http://www.crystal-creation.com/web-appli/technical-information/web-api/google/search/web/custom-search/v2.htm


Custom Search Element ControlのWebページ取込

既に、カスタム検索エンジンID「1234567890:abcdefg」(仮)を取得し、Webサイト「www.kogures.com」を検索対象に登録しています。

次の設定により、<div id="検索ボックス"></div>の個所に検索窓ができ、その直下に検索結果が表示されます。

スクリプト
<script type="text/javascript">                          // A
    var cx = "1234567890:abdefghij";
    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>

<script type="text/javascript">                          // B
    var InitCSE = function() {       // E
        var componentConfig = {
            div: "検索ボックス",                        // G
            tag: "search",
            attributes: {                                       // I
                queryParameterName: "query",
                enableHistory: true,
                enableAutoComplete: true
            }
        };
        google.search.cse.element.render( componentConfig );            // F
    }

    window.__gcse = {                               // C
        parsetags: "explicit",
        callback: function() {
            if( document.readyState == "complete" )  InitCSE();       // D
            else google.setOnLoadCallback( function () { InitCSE(); }, true );
        }
    };
</script>

HTML
<div id="検索ボックス"></div>                       <!-- H -->

標準のままだと1行全体が検索窓になるので、「.gsc-search-box {width:60% !important}」のスタイル指定をしています。