iPhone & iPod Detection Using JavaScript

By  on  

I was browsing the ESPN.com source code recently and stumbled upon their method of detecting iPhone / iPod touch users and redirecting them to their iPhone-compatible website.

The JavaScript

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
	 if (document.cookie.indexOf("iphone_redirect=false") == -1) window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR";

The code itself is short and sweet. I, however, would prefer using the server-side method of user agent checking.


if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
	header('Location: http://yoursite.com/iphone');

Which would you prefer?

Recent Features

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos


  1. Thank you so much for this post. I have a couple sites I would love to test this on to see if there is much if any difference between the two.

  2. Before everyone goes crazy implementing things like this, they should realize that some users do not want to be forced to use the mobile version. For example, I found it to be impossible to change my fantasy football lineup on ESPN.com from the iPod Touch because it kept redirecting me to their stripped-down mobile version of the site. There at least needs to be a way to override the redirection if the user so chooses.

    • Brandon Crooks

      I agree. Sometimes the water’ed down version of a site dramatically reduces usability. I’m pretty sure you can implement a link to redirect to a page without mobile redirection.

  3. I’d prefer a mobile stylesheet, but these are definitely keeper snippets. Thanks, David!

    It would be a horrible practice not to have a big link to the non-mobile version of the site, which had better have a way to detect that such a link was clicked. I’m sure people that read this know that, right?

  4. @Jeremy Parrish: Good point. I’m currently working on a mobile website and that’s one consideration I’ve taken.

  5. iPhone and the iPod touch are perfectly capable of rendering a website in full version and navigation is not a problem. I would prefer to have an option/link to go to a mobile site.

  6. Oh, btw good script to have at your disposal.

  7. Just in case anyone is interested, we had an excellent article on Dev-Tips by Brian Cray that explained how to redirect iPhone and blackberry users using .htaccess. You can find it here: http://dev-tips.com/featured/redirect-iphone-blackberry-palm-requests-with-htaccess

    Excellent article and scripting as always David.

  8. Awesome tip Drew! Your tutorial has all of the rewrite rules commented out though — you may want to change that. Thanks for commenting!

  9. Whoops, thanks for the heads up David, must have missed that when I was publishing the article. Much thanks :)

  10. Gareth

    Good script, been looking for something like this.
    I have another iPhone question:

    Is there a way of getting access to the location data (lat,lng) of the iPhone using PHP, or some other lang?
    e.g: User browses to website using safari, clicks on a button that send their lat,lng to the website.
    It is implemented on many of the apps that can be installed on the iPhone (twitterfon for example), but I’m trying to get it working on a website.

  11. tim

    I looked all over for code that worked for me. This was perfect
    (I have a flash-based site that can’t be viewed by most phones)
    However, on the mobile-centric site, I have a link to the flash site without the sniffer — which I find as an acceptable work-around to the person that was having trouble with ESPN re-directing his fantasy football site.

    Thanks so much!

  12. Thank you so much for this post. I was looking for a simple javascript method of sniffing for an iphone and re-directing to a separate page of content. This worked the first time! Thank you so much for posting this.


  13. jared

    this is great for all-flash sites…iphones can NOT render those at all. That’s exactly what i need it for, thanks!

  14. Hi David, the javascript works great. Just wondering if you got anywhere in writing that ‘view the full site here’ code? I’ve had a look around, but i think its going to need cookies and things I will just never get to grips with. Any ideas would be great!


  15. thanks, I’ve been looking exactly for this!

  16. Jaime

    @Mark Sanborn: Not true if the website is all in Flash! This script is perfect to redirect to a HTML version of the same website. Thanks for the script. Hope some day soon Iphones can run Flash.

  17. hwkd65

    got the javascript to work then all of the sudden it stopped working

    this .php version and all of the others have not worked

    .htaccess options have also not worked

    i am going to tell client to go .mobi

    need to show home page w/o flash gallery

  18. danny

    wouldnt using one of the web services like handsetdetection.com be a more effective way?

  19. @danny: This script is obviously very primitive. I’d prefer not to rely on another service if I didn’t have to.

  20. Yes, you can use JavaScript to get the location data like so:

    navigator.geolocation.getCurrentPosition( locationIs, locationNotSUpported );
    function locationIs(loc)
        // use the values
        //   loc.coords.latitude;
        //   loc.coords.longitude;
    function noLocation()
        //fallback code if no location handling
  21. (That last reply of mine was aimed @Gareth in response to his question as to whether you could get the geo information from an iPhone in a web app.)

  22. Chad Palmer

    @Mark Sanborn: Especially if they are flash based, right?

  23. Craig

    @Mark Sanborn: I put the redirection on index.html and if iPhone I goto iphonehome.html else home.html
    And then I put a link on the bottom of the iphonehome.html to link to home.html. Since home.html doesn’t have the javascript redirector they stay there. Works for me…

  24. You should note that using strstr to find if a particular string is inside another is not recommended, and that the function strpos should be used instead.


  25. Corey M

    I think is great for flash only websites who create another website specially for mobile users :)

  26. Hi,

    Thx for the information as it’s something I’ve always been curious about.

    I get the iPhone detection, but I wonder if anyone has a good lead or solution on just a very simple (HTML) or dynamic (jQuery/JS) iPhone/mobile site that can reference an image pre-existent on a flash-based site with deep linking and unique urls?

    To clarify, I’m a photographer who’s site has each image file at a unique URL. Each images lives in that gallery’s folder on my server, so when visiting my flash-based site my images aren’t locked in a shockwave or movie file on account of a backend CMS so I can add/subtract imagery.

    Any and all help, thoughts or suggestions are greatly appreciated.


  27. William Murray

    David thank you very much for this information. Some what new to this stuff where would you put this in your flash page? Thank you for the help

  28. Paul Chinetti

    Cannot Open Page
    “Safari cannot open the page because too many redirects occurred.”

    On the iPhone it flashes the correct address in the address bar, then that error pops up on the screen.

    Any suggestions?

  29. Great thank you for the post!
    Is there any way to creat a “full site” – link on the mobile site without it redirectin back to the mobile site again?

  30. Thats something I would like to know also Victor Reyes, maybe something like a url variable specifier would work..

    for example when you click Full Site the url link will be http://www.yoursite.com?mobile=no
    then use the $_GET to remove the php like…

    try that, quick run up :S

    follow me @mgpwr

  31. Thats something I would like to know also Victor Reyes, maybe something like a url variable specifier would work..

    for example when you click Full Site the url link will be http://www.yoursite.com?mobile=no
    then use the $_GET to remove the php like…


    try that, quick run up :S

    follow me @mgpwr

    • Shawn

      That’s exactly what i need but for the JavaScript redirect. Any ideas?

  32. @Paul Chinetti:

    I got the same error when i spelled the directory wrong

  33. @Mark Petherbridge:

    Thanks for the code, im yet to try it. But as far as i see would that technique mean that i have to rebuilt all the links on full site to ?mobile=no?

  34. Ant Gray

    PHP detection is better. No useless code for other browsers

  35. @Mark Petherbridge

    Works like a complete charm, great work!


  36. @Victor Reyes: You would need another $_GET function to detect that – thats what i did because i was rushing however i see no problem with reversing the script to detect when its a browser instead of an iPhone – this seems pretty cool: http://drupal.org/node/65903 for a website HOWEVER i would advise a caution because if u dnt list all browsers then it will not work..

    Im gunna be working on my site a little with this in mind – DM on twitter @mgpwr or contact me through my website http://www.mgpwr.co.uk and ill send ya code when its done….

    @Victor Reyes:

  37. This is some interesting coding :)
    Thanks a lot.

    I’m currently developing my website and it does need iDevice support!

    Thanks again.

  38. Jonathan

    Do you know if this script is good to use with other agents or are the Android and iPhones the only smart phones with browsers that read JavaScript? I found another method that covered all phones/agents, but was totally over my head, and I’m not on an Apache server. This code works great and I am so greatful for your post. Thank you.

  39. Nikos

    Nice code! Thank you!

  40. Shawn

    Victor, that’s something I’m looking for as well. I am using the JavaScript redirect, (and am a total Noob), but and wondering if you could use a variable to ignore the script, as in “if the source is “examplelink” on “mobile.my site.com” then ignore the JavaScript redirect”.

    Would using something like ?utm_source help?

  41. Thank you so much THANK YOU
    I love you so much

  42. The above JS snippet is perfect for me . Yet reading through the comments above, I wonder if just using a secondary CSS for mobile devices would be better.

    On my site I have iFrames for image scrolling. Thanks to web-kit you have to use two fingers to scroll, and it’s pretty jumpy at that. I was thinking about just putting a JS to detect mobile devices as above to do a document write to use two fingers but that is messy isn’t it?

    So what is best, a second site where I have a second CSS, and either get rid of the iFrames and replace them with normal divs, or is it to just have a mobile CSS to run on the current site?

  43. Great article! I wrote a similar article which covers Mobile Browser Detection and Redirection with Perl (http://www.mlynn.org/2010/07/mobile-device-detection-and-redirection-with-perl-and-cgi/) and PHP (http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/) The articles have downloadable example scripts as well as a test implementation at http://www.mlynn.org/uatest


  44. Gibatronic

    the code can be even simplier:

    if (/iPhone|iPod/i.test(navigator.userAgent)) {

  45. Omari

    I prefer JavaScript because I don’t think my free webhost supports PHP. Thanks for the code!

  46. Thanks man but PHP is far better

  47. Mark

    Thank you for the tip!
    I used the Javascript one and it work great! I was searching for about an hour to figure it out and POW! I found your site and it work on the first try.
    Good job! :)

  48. thanks david. you saved me… greats from izmir,turkey ;)

  49. Darren

    I’m having a bit of trouble with this. I put the code in the head of my main website (the desktop version). And went into the CP of my hosting provider and created a subdomain (the domain for the web version). I directed it to look into a specific folder for the files and when I go to the url it redirects me like it should to the web version but all the css, javascript, images (basically any links) have been stripped and don’t work/appear at all.

    Anyone have any ideas?

  50. indeed PHP is much better for user-agents detect… avoiding redirects or links altering.. like mobile.domain.com .. or domain.com/mobile .

    But as @Omari said .. or for those who do not use/have PHP available .. or any other serverside, javascript is a good idea.

    Also .. to be helpfull here are some other mobile extentions that would help.

    match(/opera mini/i)
    match(/(pre\/|palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i)
    match(/(iris|3g_t|windows ce|opera mobi|windows ce; smartphone;|windows ce; iemobile)/i')

    also .. for PHP .. use preg_match instead of strstr … is faster

  51. This method works great – I use it for http://www.digisolved.com and it works great!

  52. David

    Wow! It works perfectly!

  53. Bernie

    Hello David,

    why in all mobile site their domain starts with “m” like m.mysite.com is that only a subdomain or once the site run in mobile phones the “m” will automatically replace the www.


  54. I prefer css media, but this snippet help me to much for hiding toolbar in IOS, and not in the browsers users, preventing the user lose the point of the site when refreshing or sending a form.

    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { //if IOS do this things:
      window.addEventListener('load', function() {
        setTimeout(scrollTo, 0, 0, 1);
    }, false);  
  55. I prefer css media, but this snippet help me to much for hiding toolbar in IOS, and not in the browsers users, preventing the user lose the point of the site when refreshing or sending a form.

    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) { //if IOS do this things:
      window.addEventListener('load', function() {
        setTimeout(scrollTo, 0, 0, 1);
    }, false);  
  56. Thanks a million. It took me two days just to find this fix. :o)

  57. chris

    I’ve searched for hours for different ways of detecting browsers:
    As a designer with limited knowledge of javascript and php, this has been the only example I’ve found that makes sense and actually works. Thank you for your rare ability to explain code that i now understand and actually works for me. (I dont care if php is better, I cant get it to work and is therefore useless to me, if you want to get high and mighty, with php, write an understandable tutorial and then maybe non geeks will use it)

  58. Hey, i found to http://tinytop.mobi best detector real user agent script in the world. Awsome isn’it? :o

  59. I’m still a bit new with all this.

    Which .php file would one place the .php version of this code? PhPinfo.php?

  60. John

    For most changes, I think just detecting the screen width and swapping out styles accordingly will do what you want. After all, what you’re mostly concerned about is simplifying your page for a smaller screen. Browser sniffing has been a bad idea since 1998 and the same reasons apply now to mobile that applied then, and will lead to the same response – browsers spoofing the user agent string.

  61. inactivist

    One good reason to do this in JavaScript rather than on the server: caching. If you’re caching pages, you really don’t want to do this in PHP (or other server script).

  62. I use this to redirect to site A if on iPad/iPhone but to site B of on a other device:

        ((navigator.userAgent.match(/iPhone/i)) ||
        (navigator.userAgent.match(/iPod/i))) &&
        document.cookie.indexOf("iphone_redirect=false") == -1
        window.location = "http://site_a.com";
        window.location = "http://site_b.com";
  63. Detect all possible browsers like: proxies, desktops, tablets, mobiles and applications (java, symbian, android). This is the best code ever, enjoy ;) http://code.google.com/p/detect-real-user-agent/

    • Can you tell me the code for os detection of iphone.

  64. i want to restore my backup data from mobile to pc
    so i need to know what is the java code for that using USB device.
    Can anyone tell me..

  65. hello everybody!
    I use this code to redirect mobile user from full site to mobile version:


    My question is how to use this code to do the same thing in the other direction. I explain: i want to prevent people to pick up my jquery mobile source code by redirecting user from mobile “m.pixart.ma” version to full version “pixart.ma” if they try to open it on desktop browser.
    Thank you.

  66. Naina

    also have a question related to iphone,The thing is i am working on a desktop application of java and i want to detect the device connected to my system and check whether it is iPhone, or iPod or any other device.so can u please help me.

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

  68. Lucas

    hey if you browse with Opera you can tell the website you want to see the desktop version.

  69. Gilberto

    hello, I have an application developed in JQueryMobile and I need to make an application for IPhone to redirect to my URL.
    Can someone give me a hand?
    I could easily do to Android and now I have to do for iPhone.
    What better way.
    Thankful number attention.

  70. Niall

    Hi, I there a reason you separate it out into different match statements rather than the one regex, such as


    This statement will allow you to add on more mobile browsers such as android and opera mini without creating a big mess of or conditions, and is probably faster to just do one match. However, on my code I’ve noticed some other js on iphone acting strangely with this change, yet to determine if it is cause by an unseen js error on the iphone or if it was caused by an unrelated issue.

  71. John Nessim

    Thank you very much. Worked like a charm.

  72. John Nessim

    I added the following part to the condition and it worked perefectly with the iPad.

    || (navigator.userAgent.match(/iPad/i))

    Thanks again! :)

  73. Please I need the one that can work even for Blackberry phones.

  74. This script will tell you if a device is an iPhone, but it won’t tell you what actual device it is. For example, iOS 7 will run on iPhone 4 through 5 and 5S. For those who care, WURFL.js fixes that:


    disclosure: I work for the company that provides this, but since it’s a free service, I still think it deserves mentioning here/ Thank you.

  75. Erin

    Hi David!

    I like you version in the JavaScript flavour! Unfortunately Apple is quite strict on sharing information about the device name. For my website I use the device detection API. It is able to detect the precise device model. I use it to show iPhone cases of a specific model to a custom with that specific iPhone model.

    I hope this helps! :)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!