Aliante Search Engine Optimization | Internet Marketing Blog | SEO Web Design

phone - call us

How to detect iPhone/iPod using javascript/jQuery?
Redirecting 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

On Page:

<script>

if((navigator.userAgent.match(/iPhone/i)) ||

(navigator.userAgent.match(/iPod/i))) {

if (document.cookie.indexOf(“iphone_redirect=false”) == -1) window.location = http://www.example.com/m/; }

</script>


// 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 = "http://www.example.com/mobi/"; }

For example: if your website is www.example.com and you have a mobile version at example.com/mobi/, 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://www.example.com/mobi/"); }

 


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 */