はてなブログで Google Analytics

コピペ用

サイドバーに追加

<script>
(function() {
  var account = 'UA-XXXXX-X';

  if (!window._gaq) return;
  if (/^\/preview\b/.test(location.pathname) ||
      /[&?]preview=/.test(location.search)) return;

  var prefix = account.replace(/\W/g, '');
  _gaq.push(
    [prefix + '._setAccount', account],
    [prefix + '._trackPageview']
  );
})();
</script>

https://github.com/m4i/hatenablog-snippets/blob/master/analytics.js

モバイルページもトラッキングしたい場合は更に各記事の最後の行に追加

<script>(function(a){if(window._gaq&&!location.pathname.indexOf("/touch/entry/")){var b=a.replace(/\W/g,"");_gaq.push([b+"._setAccount",a],[b+"._trackPageview"])}})("UA-XXXXX-X")</script>

https://github.com/m4i/hatenablog-snippets/blob/master/analytics-touch.html

解説

Google Analytics 対応で気を付けるポイント

  1. はてなブログではすでにはてなのトラッキングコードが挿入されている
  2. 記事内にしか Javascript が書けないので一覧ページで複数回実行される

1 は http://code.google.com/intl/en/apis/analytics/docs/gaJS/gaJSApi_gaq.html#_gaq.push を参考にしました。
2 は複数回実行しても正しく記録されるみたいだけど、無駄な処理が走って嫌なので対応しました。

有料でもいいのではてなダイアリーのようにはてなブログが正式に対応してくれることを期待します。

一応、正式対応後でも削除しなくて問題ないようにはなってるはず。

ソースはこちら https://github.com/m4i/hatenablog-analytics https://github.com/m4i/hatenablog-snippets


2011-12-07: コードを gist から github に移しました。gist の方はそのうち削除します。