iPhone & iPod Detection Using JavaScript
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.
The PHP
if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod'))
{
header('Location: http://yoursite.com/iphone');
exit();
}
Which would you prefer?
My trip to Mozilla Summit 2013 was incredible. I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out. MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...
I was inspired when I first saw Addy Osmani's original ShineTime blog post. The hover sheen effect is simple but awesome. When I started my blog redesign, I really wanted to use a sheen effect with my logo. Using two HTML elements and...
Front-end developing is beautiful, and it's getting prettier by the day. Nowadays we got so many concepts, methodologies, good practices and whatnot to make our work stand out from the rest. Javascript (along with its countless third party libraries) and CSS have grown so big, helping...
Overflow with text is always a big issue, especially in a programmatic environment. There's always only so much space but variable content to add into that space. I was recently working on a table for displaying user information and noticed that longer strings were...
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.
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.
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.
I’d prefer a mobile stylesheet, but these are definitely keeper snippets. Thanks, David!
@Jeremy:
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?
@Jeremy Parrish: Good point. I’m currently working on a mobile website and that’s one consideration I’ve taken.
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.
Oh, btw good script to have at your disposal.
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.
Awesome tip Drew! Your tutorial has all of the rewrite rules commented out though — you may want to change that. Thanks for commenting!
Whoops, thanks for the heads up David, must have missed that when I was publishing the article. Much thanks :)
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.
Cheers
Gareth
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!
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.
Grateful.
this is great for all-flash sites…iphones can NOT render those at all. That’s exactly what i need it for, thanks!
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!
thanks,
James
thanks, I’ve been looking exactly for this!
@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.
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
wouldnt using one of the web services like handsetdetection.com be a more effective way?
@danny: This script is obviously very primitive. I’d prefer not to rely on another service if I didn’t have to.
Yes, you can use JavaScript to get the location data like so:
(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.)
@Mark Sanborn: Especially if they are flash based, right?
@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…
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.
http://php.net/strstr
I think is great for flash only websites who create another website specially for mobile users :)
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.
Mike
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
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?
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?
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
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…
[code]
[/code]
try that, quick run up :S
follow me @mgpwr
That’s exactly what i need but for the JavaScript redirect. Any ideas?
right ok go here for code:
http://www.mgpwr.co.uk/code.txt
@Paul Chinetti:
I got the same error when i spelled the directory wrong
@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?
PHP detection is better. No useless code for other browsers
@Mark Petherbridge
Works like a complete charm, great work!
Thanks.
@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:
This is some interesting coding :)
Thanks a lot.
I’m currently developing my website and it does need iDevice support!
Thanks again.
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.
Nice code! Thank you!
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?
Thank you so much THANK YOU
I love you so much
Thnaks
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?
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
Enjoy!
Mike
the code can be even simplier:
if (/iPhone|iPod/i.test(navigator.userAgent)) {
// HELL YES! WE GOT AN IPHONE OR IPOD HERE!
}
I prefer JavaScript because I don’t think my free webhost supports PHP. Thanks for the code!
Thanks man but PHP is far better
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! :)
thanks david. you saved me… greats from izmir,turkey ;)
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?
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(/android/i)
match(/opera mini/i)
match(/blackberry/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
This method works great – I use it for http://www.digisolved.com and it works great!
Wow! It works perfectly!
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.
Thanks
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.
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.
Thanks a million. It took me two days just to find this fix. :o)
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)
Hey, i found to http://tinytop.mobi best detector real user agent script in the world. Awsome isn’it? :o
I’m still a bit new with all this.
Which .php file would one place the .php version of this code? PhPinfo.php?
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.
Here how to do this with C# in ASP.NET:
http://www.thebestdata.com/zoom.aspx?menutype=1&auto=3667&t=C#-ASP.NET-detect-mobile-device
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).
I use this to redirect to site A if on iPad/iPhone but to site B of on a other device:
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.
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..
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.
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.
if(navigator.userAgent.match(/iPhone|iPod/i))
hey if you browse with Opera you can tell the website you want to see the desktop version.
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.
Hi, I there a reason you separate it out into different match statements rather than the one regex, such as
navigator.userAgent.match(/iPhone|iPod/i);
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.
Thank you very much. Worked like a charm.
I added the following part to the condition and it worked perefectly with the iPad.
|| (navigator.userAgent.match(/iPad/i))
Thanks again! :)
Please I need the one that can work even for Blackberry phones.
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:
http://wurfljs.com/
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.
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! :)