Platform and browser detection in your webapp

Just imagine this scenario: Your webapp tries to start the native Facebook app with your own fanpage automatically opened. Depending on your mobile operating system, you would have to use different approaches to get there. Feature detection fails – we have to dig deeper.

While searching the web for ways to detect a user’s browser or platform, you might often find information about Modernizr, which is a neat JavaScript tool to detect which CSS and JS features you can use. This comes in handy, if you just need to know which options you have in terms of visualization and presentation. If you, however, need to know whether a user is visiting your page or app from an iPhone or Android device, you will have to fall back on an uglier solution, which might be a necessary evil sometimes.

Back to our use case from earlier: Feature detection will only get you so far, so you have to mess around with the user agent strings in order to get information about the platform.

The simplest case would be to parse the user agent (use the navigator object in JavaScript: navigator.userAgent):

 // check user agent for platform string and set url accordingly
   fb_app_link = "fb://profile/1234567890/";
}else if (navigator.userAgent.match(/android/i)) {
   fb_app_link = "fb://page/1234567890/";
}else if (navigator.userAgent.match(/Windows Phone/i)) {
   fb_app_link = "fb:pages?id=1234567890";
}else {
   fb_app_link = "https://www.facebook/pages/abcdefgh/1234567890";
// redirect browser to the correct url

This way you don’t rely on third-party code and have an extremely simple way of detecting the user’s platform to make your app work the right way.

Unfortunately though, the user agent is volatile, because every browser lies about their rendering engine, name etc. This makes it extremely difficult to correctly predict the browser at hand.

If you absolutely need to know the browser, you could use tools like WhichBrowser or Bowser, which try to cope with the issues regarding user agents by taking other information into account as well or simply by  handing you the browser and platform properties as a nice JavaScript object. Need to check for Chrome on Android? How about if( && { /* magic */ }? Neat.

But even though WhichBrowser seems like a well-thought-out solution for browser detection, they state the following on their GitHub page:

“This is an extremely complicated and almost completely useless browser sniffing library. Useless because you shouldn’t use browser sniffing. So stop right now and go read something about feature detecting instead. I’m serious. Go away. You’ll thank me later.”

Libraries are not your thing or you just need a quick and dirty solution? Fret not! You could always try your luck with a custom approach like this one. You achieve this by sifting through the provided information yourself. Look for known bits and pray to a deity of your choice that it will work sufficiently for your cause.