Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the User Agent with JavaScript

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" /> 
like image 287
henryaaron Avatar asked Feb 26 '12 02:02

henryaaron


People also ask

What is JavaScript user agent?

User-Agents is a JavaScript package for generating random User Agents based on how frequently they're used in the wild. A new version of the package is automatically released every day, so the data is always up to date.

How do I find the user agent?

Click Develop > User Agent and select the user agent you want to use in the list. If the user agent you want to use isn't shown here, select “Other” and you can provide a custom user agent. You can find extensive lists of user agents on various websites, such as this one.

How can you detect the client's browser name in JavaScript?

You can use the navigator. appName and navigator. userAgent properties. The userAgent property is more reliable than appName because, for example, Firefox (and some other browsers) may return the string "Netscape" as the value of navigator.


1 Answers

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">
like image 184
Adam Merrifield Avatar answered Sep 23 '22 19:09

Adam Merrifield