Question

I have coded few lines of java script code. But I am not sure that it is correct or not. Few months back I published a desktop version website. but when a user coming through a mobile (like android, iPhone or may be windows phone), I want to redirect a new path. Here is the code:

// JavaScript Document
var uAgent = navigator.userAgent.toLowerCase();

if(uAgent.indexOf("android") > -1 || uAgent.indexOf("iphone") > -1 || uAgent.indexOf("windows phone") > -1) {
    window.location = "http://website path will come here.";
}

Is it the correct code?

Was it helpful?

Solution

That will work, but its not a great way to do this for a couple of reasons:

  1. Users with JavaScript disabled will not get redirected

  2. Mobile users (some with slow browsers and tight bandwidth limits) will download your desktop page before being redirected to the mobile site.

A better approach if possible, would be to manage this via the web server configuration ideally without any redirects at all. Alternatively, consider serving the same content to all users and changing the layout with media queries.

OTHER TIPS

If you really need to detect a mobile browser (instead of making a mobile-friendly responsive layout like the Responsive template on Initializr that Just Works on mobile browsers - Google for "mobile first" and "responsive design" for more examples) then take a look at these links:

There are tons of mobile browsers - not only iPhone, Android and Windows - so if you are going to detect them then you need to do it right. See also the jQuery Mobile, a great mobile framework that will make your life easier.

uAgent.indexOf("android") > -1

Android is not just an operating system for smartphones. It also runs on a lot of tablets which can easily handle the desktop-optimized versions of most websites. A friend of mine just complained that some websites only serve the mobile version to his GalaxyTab, even though the normal version would look well on his 10.1" screen.

You also forgot about blackberry and symbian phones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top