89

I'd like to get a script that can grab the user's user agent and prop it to an attribute.

I'm making a website problems contact form and I usually need to know what browser the user is using. How can I detect the user agent string and prop it as the value of an input element.

My html looks something like:

<input type="hidden" id="UserAgent" name="User Agent" />

I want the user agent to be added to that as the value attribute so it would look like:

<input type="hidden" id="UserAgent" name="User Agent" value="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.53.11 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10" />
Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
henryaaron
  • 5,648
  • 18
  • 54
  • 78
  • 4
    You should not need any JavaScript to do this. Just read the user-agent-string from the HTTP header. – Bergi Sep 29 '12 at 10:22
  • 9
    @Bergi: Actually that's only if you want it at the server-side. With JavaScript - **`navigator.userAgent`** should suffice as per accepted answer. – Robin Maben Aug 13 '13 at 12:45
  • 1
    @Robin: OP *is* asking for server side, he wants to get the UA string posted with his contact form. – Bergi Aug 13 '13 at 13:01
  • 4
    Not if you are generating parts of your application client side. Which seems to be what he was doing. – oligofren Jan 22 '14 at 11:23

2 Answers2

181

Pure Javascript

document.getElementById('UserAgent').value = navigator.userAgent;
<input type="text" id="UserAgent">

jQuery

$('#UserAgent').val(navigator.userAgent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="UserAgent">
Adam Merrifield
  • 9,819
  • 4
  • 37
  • 54
  • 8
    Please add a non-JQuery alternative to the answer. So many new developers think that jQuery _is_ Javascript :-( – Mark Cooper Aug 05 '15 at 06:28
  • Will not work in jQuery 1.9 or later unless the jQuery Migrate plugin is included. – Davlio Apr 24 '17 at 22:42
  • @Davlio this is not true. The example itself is using jQuery 1.11.1 and does not use the Migrate plugin. – Adam Merrifield Apr 26 '17 at 01:17
  • @AdamMerrifield you are right! i said for [`$.browser`](https://api.jquery.com/jquery.browser/) and dont could edit the comment. – Davlio Apr 26 '17 at 01:44
51

Original Q didn't say anything about jQuery. so

document.getElementById('UserAgent').value = navigator.userAgent;
axlotl
  • 1,342
  • 1
  • 10
  • 18