6

We have developed a website which has general homepage and mobile page, one is for mobile and other is for PC.

I want code to detect the device automatically and navigate to the mobile homepage if the user is from mobile and navigate to the homepage(general) if the user is from PC and problem is it should be using JavaScript or plain HTML.

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
user1134567
  • 61
  • 1
  • 1
  • 2
  • possible duplicate of [How to detect a mobile device with javascript?](http://stackoverflow.com/questions/6666907/how-to-detect-a-mobile-device-with-javascript) – Manse Jan 06 '12 at 15:27
  • Or this one -> http://stackoverflow.com/questions/1005153/auto-detect-mobile-browser-via-user-agent – Manse Jan 06 '12 at 15:27
  • Why would you do this with JavaScript and not the server? – epascarello Jan 06 '12 at 15:28

4 Answers4

7

http://detectmobilebrowsers.com/ has an open source javascript function to detect a mobile browser that you can use.

ronme
  • 1,154
  • 1
  • 11
  • 18
  • 2
    do you know of any examples about using it? I looked at the website and page source code. It is so unclear how to use its javascript version. Thanks! – curious1 Dec 16 '13 at 18:39
2

To determine this you need to check the HTTP header for the request for your website, in particular the User-Agent string.

You haven't mentioned what technologies you're using, but you can redirect at the web-server level or within your application.

m.edmondson
  • 30,382
  • 27
  • 123
  • 206
  • 2
    From your link: *User agent sniffing is now considered poor practice, ... Instead, the W3C recommends creating HTML markup that is standard, allowing correct rendering in as many browsers as possible, and to test for specific browser features rather than particular browser versions or brands.* – Sablefoste Feb 11 '16 at 19:34
  • @Sablefoste - Agree feature 'sniffing' is now considered better practice. I did write the answer 4 years ago :-) – m.edmondson Feb 12 '16 at 08:41
2

Don't make separate sites. Use reactive design. The browser on my phone is just as good as the one on my desktop.

tkone
  • 22,092
  • 5
  • 54
  • 78
  • Reactive design is a bit vague in this context. It can be useful to conditionally navigate to a separate page where mobile can be assumed allowing for removal of bloated elements in the server response like heavy images, scripts, and stylesheets. Or where the context of use for mobile is drastically different from desktop. Simply serving a one page reactive document is not always the best approach, as addressed in Ethan Marcotte's Becoming Responsive chapter in Responsive Web Design (from A Book Apart). – Rich Jan 11 '13 at 17:07
0

you can use below code,

var index = navigator.appVersion.indexOf("Mobile");

This will return you negative value if the request is not from mobile site.

Happy learning :)

Basavaraj Hadimani
  • 1,094
  • 12
  • 21