LoginSignup
10
9

More than 5 years have passed since last update.

【JavaScript】ユーザーエージェントの取得と変更

Posted at

JavaScriptでは、navigatorオブジェクトのuserAgentプロパティからユーザーエージェントが取得できます。

使用しているOSやブラウザの情報を取得できるので、環境ごとに違う内容を返したいときに利用できます!

フリー百科事典『ウィキペディア(Wikipedia)』〜ユーザーエージェント

JavaScriptリファレンス〜navigator.userAgent

コンソールで確認

コンソールで下記のコードを実行するだけです。

console.log(navigator.userAgent);

サンプルコード

こちらもどうぞ。

useragent_test.html
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>userAgentの表示</title>
</head>

<body>
  <p id="result"></p>

  <script>
    var userAgentResult = navigator.userAgent;
    document.getElementById("result").innerHTML = userAgentResult;
  </script>
</body>

</html>

ユーザーエージェントの変更

ブラウザで変更可能です。
例えば、Mac上でWindowsの場合の動作を確認したいときに。(実機確認も必要ですが・・・)

Chromeで変更する方法

  1. デベロッパーツールを開く
  2. 右上の縦三点リーダー(Customize and control Dev Tools)をクリック
  3. More toolsを選択
  4. Network conditionsを選択
  5. User AgentSelect automaticallyのチェックを外し、好みの「ブラウザ-OS」を選択

判定方法

IndexOfメソッドで地道に文字列を判定する。
しかし、ブラウザによる挙動の違いに注意。

MDN web docs〜User Agentを用いたブラウザーの判定

プラグインがあれば入れておくと良さそうです。

UserAgentからOS/ブラウザなどの調べかたのまとめ

10
9
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
10
9