Often there may be a requirement to redirect a user to a mobile friendly version of a website.
In many cases a responsive layout is only the first step to a ideal user experience. Due to mobile data usage restrictions, some websites will need to reduce the resource load of assets (which were created for desktop environments) by swapping to smaller, more compressed versions… OR be responsible for the wrath of a user who has exceeded their data cap because of your website.

To avoid the latter, your website should determine if a user is visiting from a mobile device and adjust accordingly.

Continue reading to learn how to do so with JavaScript.

To do so, we need to access the ‘navigator.userAgent’. The userAgent returns comprehensive information on the users browser.

you can test it on desktop by typing the following into a html document and checking your browser output window

<script type="text/javascript">
   console.log(navigator.userAgent)
</script>

It should return something like this

“User-agent header sent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11”

Below is a mobile usage example which will redirect users if they are using any of the listed devices.
Place the script between your opening and closing ‘head’ tags.


<script type="text/javascript">

console.log(navigator.userAgent)
if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 ){
//user is on mobile, redirect them to mobile friendly page
window.location = "http://www.yourwebpage.com/mobile/"
}
else 
{ 
//user is on a desktop, dont redirect
window.location = "http://www.yourwebpage.com"
}

</script>

**NOTE: There have been many discussions on how ‘fool proof’ this method is. At the time of writing this, it was working with all major devices.
As new devices come out the userAgent data may be more cryptic. I will try to update this post if there are any changes. Test where possible.