Alan Edwardes

Detecting The Awesomeness That Is Mobile Safari

For Christmas I got an iPod touch - and I can't believe how awesome it is. Not one to go for the clickywheel on the other traditional iPods, I decided that I would support Steve Jobs in his mission to abolish buttons by asking Santa for an iPod Touch. Pah, iPhones are too expensive.

I also adore Mobile Safari, so much so in fact that I created a small PHP and JavaScript function to detect whether the user is using an iPod Touch or an iPhone to browse your site. I felt that I needed to write one because Mobile Safari seemed to break my site design with weird font sizes, so I removed the comments section and made my homepage slightly more compact just for users sporting a shiny Mobile Safari user agent.

Two functions to detect Mobile Safari in different ways:

The PHP Function

Offering server side awesomeness, this is probably the best technique for detecting mobile Safari if you use PHP for your site.
function ismobilesafari(){
	return preg_match('/(iPod|iPhone|iPad)/', $_SERVER['HTTP_USER_AGENT']);
}

Example usage, to echo a message to the user:

if( ismobilesafari() ) {
    echo( "It's Mobile Safari." );
} else {
    echo( "Nope, it's another browser." );
}

The JavaScript Function

The client side coolness still works, except some weird people disable JavaScript on their iPod/iPhone, so might not work 100% of the time.
function ismobilesafari(){
	return navigator.userAgent.match(/(iPod|iPhone|iPad)/);
}

Example usage, to echo a message to the user:

if( ismobilesafari() ) {
    document.write( "It's Mobile Safari." )
} else {
    document.write( "Nope, it's another browser." )
}

Screenshotz

Both of the functions + examples above will result in the following:

  

View a live demo. (View the source of the page to see both methods)

3 Comments

Hendrik Runte's Gravatar
1

Now that a third device (iPad) has arrived, you should update your JS function:

{code} if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) { alert("It's mobile safari."); } {code}

Alan Edwardes's Gravatar
2

Thanks, done that. Also switched to a regex match instead of multiple if statements to reduce the need for repeated code.

Joseph Taylor's Gravatar
3

Good job with this function. Nice and simple and using regex makes it all the better.

Add a Comment

26th of December 2008 at 7:12 PM

3 years, 4 months ago

written by Alan Edwardes.

297 words

3 comments so far

feed for comments on this post

rand: "Strong" HTML 5 Support in ...

next: Left 4 Dead

prev: Windows Live Web Refresh

share:FacebookTwitterRedditdiggStumbleUpondeliciousHacker NewsLinkedIn

add a comment

© 2006 – 2012 Alan Edwardes / code on github
Top