LoginSignup
12
17

More than 5 years have passed since last update.

JavaScriptでUserAgentを取得する

Posted at

今日、JavaScriptを使用してUserAgentを取得してゴニョゴニョするという機能を実装した。
はじめて「JavaScriptでのUserAgentの取得」ということをしたので、以下参考にどうぞ。

前提条件

  • 特に無し

UserAgentを取得し、これを画面上に出力する。(画面への出力に関してはjQueryを使用。)
HTMLファイルにまとめると、以下のようになる。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>UserAgent Sample</title>
</head>
<body>
<span id="userAgent"></span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        var userAgent = window.navigator.userAgent.toLowerCase();
        $('span#userAgent').text(userAgent);
    });
</script>
</body>
</html>

scriptタグの中のwindow.navigator.userAgentでUserAgentを取得することができる。
あとはこの中身を解析して、OSやブラウザの情報を調べることができる。

ただし、UserAgentの情報は偽装することが可能なので、超厳密に調べる場合にはこの方法では不十分なようです。悪しからず。

参考

12
17
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
12
17