I am working on web analytics. I am using JavaScript client-side and NodeJS server-side. I know we can find out device type using userAgent
, but how do I detect the device brand (client or server side)?
问题:
回答1:
You can't do it directly; the userAgent field simply does not contain the vendor. However you can build up a library of userAgent tokens which map to particular vendors. This will involve a lot of research and testing on a wide range of devices, though.
For example, anything with "iOS", "iPhone" or "iPad" in the userAgent you can safely map to "Apple". Then the Samsung Galaxy S3, for example, has the model number in the userAgent, which is "GT-I9300". You can then map this to "Samsung". ...and then you'd need to repeat this for every other device you want to recognise. Looking up user agent strings online is probably the quickest way.
回答2:
One library that parses this out for you is Platform.js, and you can use it either client-side or server-side as described in their intro page linked above.
Here's a client-side example:
<script type='text/javascript' src='platform.js'></script>
<script type='text/javascript'>
alert('you are using ' + platform.description + ' on an ' + (platform.manufacturer || 'unknown vendor') )
</script>
Note that you will get no manufacturer on generic browsers but should get the brand on mobile devices e.g. Apple, Samsung, etc.
回答3:
At Server side, you can do this very easily using device npm module and if you are using Express.js then it's easy as cake.
Install module.
npm i --S express-device
Add in the express code as middleware.
var express = require('express');
var app = express();
var device = require('express-device');
app.use(device.capture());
app.get('/hello',function(req,res) {
res.send("Hi to "+req.device.type.toUpperCase()+" User");
});
app.listen(3000);
console.log("Listening to Port 3000");
Simple and sweet.
Reference : https://codeforgeek.com/2016/07/how-to-detect-device-type-in-nodejs/
回答4:
the Detection via userAgent Strings can cause errors in your detection. You can change the Browser String to whatever you want. In the most cases it doesnt tell you which device it is.
回答5:
Every data you might get from your client might be spoofed so don't expect every user to transmit only 100% correct data.
But you can get the clients useragent via req.headers['user-agent']
in nodeJS and here is a list of many mobile browsers.
回答6:
In my case ua-parser-js was the best free solution. The minified version is on https://github.com/faisalman/ua-parser-js/tree/master/dist
What you need to do then is like
<script src="ua-parser.min.js" charset="utf-8"></script>
<script type="text/javascript">
var parser = new UAParser();
var result = parser.getResult();
alert(result.device.vendor);
</script>
I have tried platform.js and mobile-detect.js before this one, but their detection range was too narrow for my application.