In this post you will learn how to detect iPhone/iPod using javascript/jQuery, redirect your iPhone users to mobile version of your site using javascript and alternative and better way to redirect your visitors using server-side PHP code snippet.
The latest buzz around jQuery is upcoming jQuery mobile – support for mobile devices. Current jQuery core work fine on iPhone and iPod touch browsers and most of us have created a mobile version of our websites, developed or converted websites for others. Basically, jQuery is already being used on iPhone and iPod touch devices. Without any further ado…
Javascript code to detect iPhone and iPod browsers
// Return boolean TRUE/FALSE function isiPhone(){ return ( (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) ); }
You might wonder why do we even need to detect if our website is ran on iPhone Safari or normal desktop Safar if jQuery works fine on both. Well, there are Safari specific CSS features that you might want to utilize and you need to know if the current browser is Safari, then you may also want to consider reducing resource consuming features like animations for iPhone version of your site.
Redirecting iPhone & iPod users
You may also use this script to redirect iPhone and iPod users to your website’s mobile version:
// Redirect iPhone/iPod visitors function isiPhone(){ return ( (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1) ); } if(isiPhone()){ window.location = "mob.example.com"; }
For example: if your website is www.example.com and you have a mobile version at mob.example.com, then put the following script to your www.example.com.
Redirect iPhone users using PHP
It is better to detect and redirect your iPhone users on the server-side. Here is a PHP code to redirect iPhone users:
// Redirect iPhone/iPod visitors if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod')){ header("Location: http://mob.example.com"); }
User agent strings for your reference:
/* User Agent String for iPhone Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 User Agent String for iPod Touch Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3 */
As final words, I would like to remind you that sometimes your visitors would not like to be redirected to mobile versions of your websites. That’s why your mobile version should always include a link to your non-mobile website. The above scripts can be rewrote to check if user has chosen not to be redirected. Either set cookie or a URL parameter.