0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

3つのデバイスタイプを判別する3つの方法

Last updated at Posted at 2019-12-04

Webサイト訪問者の3種類のデバイス(モバイル、タブレット、デスクトップ)のデータを取得するコード

1. ユーザーエージェントで判別する方法


function device(){
  return /iPad/.test(navigator.userAgent)?"tablet":/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Silk/.test(navigator.userAgent)?"mobile":"desktop";
}

参照したサイト:どこかのECサイト

2. ウィンドウの大きさで判別する方法

function device(){
  var width = window.innerWidth,
    screenType;
  if (width <= 520) {
    screenType = "mobile";
  } else if (width <= 820) {
    screenType = "tablet";
  } else {
    screenType = "desktop";
  }
  return screenType;
}

参照したサイト:
https://www.upbuild.io/blog/device-specific-gtm-tags/

3. 何やら外部のコードを使う方法(ユーザーエージェントで判別)

//mobile-detect.js(https://github.com/hgoebl/mobile-detect.js/)を利用

function device(){
  var md = new MobileDetect(window.navigator.userAgent);
  var mobile = md.phone() ? "mobile" : undefined;
  var tablet = md.tablet() ? "tablet" : undefined;
  return mobile || tablet || "desktop";
}

参照したサイト:
https://github.com/hgoebl/mobile-detect.js/
https://support.google.com/tagmanager/forum/AAAAnP_FwdICvO-Fx7PeW8

背景

  • 広告サービスCriteoのサーバーに送信するデータとしてデバイスタイプを取得しておく
  • このJavascriptコードはタグマネジメントツール(GoogleタグマネージャーのカスタムJavascript)に設置する
  • (※上記背景の場合、実際には関数名や返すデバイスタイプの値を少し修正する)

何かあればお手数ですが、本記事か以下アカウントでお知らせください!

\ Follow Me! /
Qiitaアカウント
Twitterアカウント

0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?