Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That's very straightforward. Obviously the user agent is reported by the browser/device as mobile or not (it either includes that keyword or not). In nearly all cases mobile means smartphone or tablet, whether Android or iOS, Chrome or Safari. iPad commonly includes the mobile keyword in its user agent string, unless desktop is enabled by default and then they'll just get the desktop version (you could trivially detect for the iPad keyword and force mobile; given the userbase size of iPad it would probably be worth it, it'd take seconds to do). This approach covers such a comprehensive percentage of users that it's only going to be an issue if you absolutely need to cover every single possible variation, and then you have to do it another way to go from 99% to 100%.

Your desktop browser doesn't include the keyword "mobile" in the agent string. Your Safari browser on iOS does, ditto for Chrome on Android.

So here's the iPhone 13 Max user agent string:

"Mozilla/5.0 (iPhone14,3; U; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/19A346 Safari/602.1"

The "mobile" keyword gets you what you want.

Here's iPhone 8:

"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1"

The "mobile" keyword gets you what you want.

ChromeOS desktop (Chrome browser), Mac desktop (Safari), Windows desktop (eg Chrome or Firefox). They don't include the "mobile" keyword.

It's not flawless, getting to 100% requires a lot more effort. This approach is far beyond good enough however, particularly for an average site. If you're building a giant enterprise app and want to appeal to every possible user and you have a team, maybe you'll throw a lot more resources at getting the small number of problematic edge cases.

And if you're using Nginx, which I commonly do, you can map the agent key in your http segment, eg:

map $http_user_agent $mobilekey {"~*Mobile" mobile; default desktop;} (or vise versa)

and then you can utilize that for caching related tasks (attach it to your proxy_cache_key to differentiate a mobile vs desktop cache).

And as I've noted, this is widely despised by the HN crowd despite the fact that it works so well and so easily.



"works so well" is debatable. Is iPad "mobile" (honestly, I'm not sure). What if I'm on desktop and I make my screen just a bit smaller? Can I now not use the website because it doesn't bother adapting to the changing width.

If this is how you want to build websites, discarding users, go ahead. But it's irresponsible to recommend this as advice to others.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: