Mobile detection

V2boni picture V2boni · Apr 13, 2009 · Viewed 54.9k times · Source

Is there a way to detect mobile devices using Javascript? Also, I researched that there are such an XML which contains user-agents that could help to identify the mobile handsets.

Answer

Dagg Nabbit picture Dagg Nabbit · Aug 10, 2011

You probably have a normal site and you want to redirect to a mobile site if certain conditions are met, like the screen is very small, or the content is zoomed out to fit on a large "virtual" screen in a small physical space. So, why not check for those conditions instead of testing a zillion UA strings.

Try something like this:

For the UA to report the screen's physical pixel size, this tag must be present in the html page. *

<meta name="viewport" 
      content="width=device-width, initial-scale=1, maximum-scale=1" />

Now, just get the size of the screen and redirect if needed. Use a slight delay. **

setTimeout(function(){
  if ((screen.width < 480) || (screen.height < 480)) {
    location.replace('/mobile/');
  }
}, 100);

That's pretty much it. Since this page already has the viewport tag set up for mobile, you could also do the inverse, show mobile here and redirect to full site if screen is bigger.

Edit: I'm not sure why this question has been closed; as far as I can tell it fits the SO format pretty well. Voted to reopen.

* Inserting it with javascript doesn't seem to work (someone please correct me if you figure out a way). If it isn't present, the phone will report a virtual screen size that is larger than the actual screen. It also doesn't seem to work in iframes, only top level windows (which makes sense because iframes will need to be scaled the same amount as the outer window, they share the same viewport).

** Some mobile browsers keep the viewport size from the last loaded page, so they report a large virtual screen size for a few milliseconds, until they notice the meta tag I guess. I couldn't find an early event to hook this into, please comment if you have a better way of doing this. 50 ms delay worked fine in all my tests, 100 should be mostly safe.