2
0

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 1 year has passed since last update.

JavaScriptでパソコン・タブレット・スマホを判別する

Posted at

スマホとPCで処理の仕方を変える方法の紹介。今までは画面幅で判別してきたが、今回はアクセスしてきた端末のユーザーエージェントを取得、解析して判別する方法のメモ。

    function device() {
      const ua = navigator.userAgent;
      if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0){
          return 'mobile';
      }else if(ua.indexOf('iPad') > 0 || ua.indexOf('Android') > 0){
          return 'tablet';
      }else{
          return 'desktop';
      }
    }

    window.onload = function() {
      console.log(device());
    }

device()の返り値で端末を判断できます。
ただ、navigator.userAgentは将来的に非推奨とし、凍結するそうで、代替としてUser-Agent Client Hintsが策定中みたい。今後はそちらを使用していく。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?