LoginSignup
2
2

More than 5 years have passed since last update.

gtag.jsのイベントをユーザーエージェント毎に変える

Last updated at Posted at 2018-02-20

もしかしたら使うかもしれないので、作ったやつ。

HTML
<a class="js-gtag" id="link01" href="#">リンク1</a>
<a class="js-gtag" id="link02" href="#">リンク2</a>
JavaScript
const ua = navigator.userAgent.toLowerCase();
const isMobile = /i(phone|pod)/.test(ua)||/android(.+)?mobile/.test(ua);

const _importGtag = function(target, category, action) {
  const $gtagTarget = $(`.${target}`);

  $gtagTarget.each(function() {
    let $this = $(this);
    let _id = $this.attr('id');

    let _ua;
    if (isMobile) {
      _ua = 'mobile';
    } else {
      _ua = 'notMobile';
    }

    let _event = `gtag('event', '${action}', {'event_category': '${category}', 'event_label': '${_id}_${_ua}'});`;

    $this.attr('onclick', _event);
  });
};

// _importGtag('クラス名', 'カテゴリー', 'アクション');
_importGtag('js-gtag','category_name','action_name');

スマホでリンク1をタップすると、event_labellink01_mobileになる。
それ以外でリンク2をクリックすると、event_labellink02_notMobileになる。

以上。

2
2
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
2
2