iPhone 'user agent' FAQ: I'm trying to optimize my HTML/web app for the iPhone; how do I detect an iPhone, iPod, or iPad browser in my web application?
This Apple page shows the iPhone, iPod, and iPad user agent strings, so you just need to write some JavaScript that properly parses those iPhone/iPad browser user agent strings.
Here's what the iPhone user agent string looks like for iOS 2:
Mozilla/5.0 (iPhone; U; CPU iOS 2_0 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/XXXXX Safari/525.20
That's actually one long string, but I wrapped it here to reduce scrolling.
As you can see, the string "iPhone" is contained in that user agent text, so a simple way of searching for the iPhone string in the user agent text with JavaScript looks like this:
var isIphone = navigator.userAgent.indexOf("iPhone") != -1 ;
That statement makes the variable isIphone true if the string "iPhone" is seen in the browser user agent text, or false if the text is not found.
Detecting iPhone, iPod, or iPad user agents
You can use just that one line if you're really only concerned about detecting the iPhone in your HTML application, or you can also perform other checks for the iPod and iPad to detect all iOS devices:
var isIphone = navigator.userAgent.indexOf("iPhone") != -1 ; var isIod = navigator.userAgent.indexOf("iPod") != -1 ; var isIpad = navigator.userAgent.indexOf("iPad") != -1 ; // now set one variable for all iOS devices var isIos = isIphone || isIpod || isIpad ;
Now that you've properly detected the iPhone, iPod, or iPad devices in your web application using JavaScript, you can use the isIos variable (or the other JavaScript variables we created) in your JavaScript decision-making process.
iPhone/iPad user agent detecting - More information
For more information on detecting iPhone and iPad user agents, see this Apple documentation page. For a JavaScript library which was made for detecting Apple WebKit devices, see this link on detecting WebKit.
iPhone/iPad web app user agent detecting - Summary
I hope this tip on using JavaScript to detect iPod, iPhone, and iPad devices in your HTML/web apps has been helpful. When you're trying to optimize your web app to look as much as possible like a native iPhone app, you just need little tips like this to optimize the HTML (and JavaScript) in your web app.