Getting the User Agent with JavaScript
Asked Answered
A

2

102

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" />
Allgood answered 26/2, 2012 at 2:42 Comment(4)
You should not need any JavaScript to do this. Just read the user-agent-string from the HTTP header.Elbe
@Bergi: Actually that's only if you want it at the server-side. With JavaScript - navigator.userAgent should suffice as per accepted answer.Deluca
@Robin: OP is asking for server side, he wants to get the UA string posted with his contact form.Elbe
Not if you are generating parts of your application client side. Which seems to be what he was doing.Motion
E
198

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">
Exaggeration answered 26/2, 2012 at 2:45 Comment(4)
Please add a non-JQuery alternative to the answer. So many new developers think that jQuery is Javascript :-(Andresandresen
Will not work in jQuery 1.9 or later unless the jQuery Migrate plugin is included.Potomac
@Potomac this is not true. The example itself is using jQuery 1.11.1 and does not use the Migrate plugin.Exaggeration
@AdamMerrifield you are right! i said for $.browser and dont could edit the comment.Potomac
E
52

Original Q didn't say anything about jQuery. so

document.getElementById('UserAgent').value = navigator.userAgent;
Endmost answered 11/6, 2014 at 19:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.