Java Servlets - How do I detect if a user is from a mobile device?
I'm using the TinyMCE javascript editor, and it doesn't work on the iphone. How can I detect if the user is coming from a mobile device?
You get a header / message from a device. All you know about the device is in the header and the device can write what it wants in it. If you are talking about http requests (which is indicated by agent lookup) you can look at a header here: All you can do "reliable" is to look for the user agent.
To detect if the user is using a mobile device in JavaScript, we can use the userAgent property. This property is part of the navigator object and sent by the browser in HTTP headers. It contains information about the name, version, and platform of the browser.
I have used the UAgentInfo.java class you can download here (http://code.google.com/p/mobileesp/source/browse/Java/UAgentInfo.java):
private boolean isRequestComingFromAMobileDevice(final HttpServletRequest request){
// http://www.hand-interactive.com/m/resources/detect-mobile-java.htm
final String userAgent = request.getHeader("User-Agent");
final String httpAccept = request.getHeader("Accept");
final UAgentInfo detector = new UAgentInfo(userAgent, httpAccept);
return detector.detectMobileQuick();
}
The UAgentInfo class has a bunch of methods to detect particular devices as well. Just replace detector.detectMobileQuick() for, for instance, detector.detectIphoneOrIpod(), detector.detectKindle(), etc.
UPDATE: If you use Spring, you might want to use its native implementation instead. Here is an example: http://spring.io/guides/gs/device-detection/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With