LoginSignup
3
8

More than 5 years have passed since last update.

Googleカスタム検索エンジンの設置方法

Last updated at Posted at 2017-03-30

Googleカスタム検索の設置メモです。
V2は後で追記するかもです。
どこか間違いがありましたら、ご指摘いただけると幸いです。
※2019/4/2更新 <gcse:searchbox-only><gcse:searchresults-only>を使うとMarkup Validation Serviceに引っかかる為、HTMLタグを使用した方法に変更しました。
属性を追加する場合は、プレフィックス「data-」を付ける必要があります。

前提条件

  • Googleアカウントをこちらで管理していない。
  • 別に検索結果ページ作成。
  • 検索結果ページは、検索窓と検索結果が別エリア(デザインのレイアウトオプションを2列に設定してもらっている)
  • 通常ページは検索窓のみ。

Custom Search Element Control API

制御にJavaScriptを使用しない方法です。
まずは下記コードを貼り付けます。

<script>
  (function() {
    var cx = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    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>

通常ページ

検索窓を表示したい箇所に下記を追加します。

<div enableHistory="true" class="gcse-searchbox-only" data-resultsUrl="検索結果ページのURL" data-queryParameterName="search"></div>
  • 「resultsUrl」で検索結果ページのURLを指定。
  • 「enableHistory」でブラウザの[戻る]および[進む]ボタンを押しても履歴が残るようにします。
  • 「queryParameterName」でクエリパラメータ名を追加

検索結果ページ

検索窓

<div enableHistory="true" class="gcse-searchbox-only" data-queryParameterName="search"></div>
  • 「enableHistory」でブラウザの[戻る]および[進む]ボタンを押しても履歴が残るようにします。
  • 「queryParameterName」でクエリパラメータ名を追加

検索結果表示エリア

<div class="gcse-searchresults-only" data-linkTarget="_self"></div>
  • デフォルトは「_blank」で別ウィンドウで開いてしまうので、「linkTarget」で「_self」に変更。

参考サイト

Custom Search Element Control API
Googleカスタム検索によるサイト内検索機能の利用方法
Google API プログラミング解説

3
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
8