Created
November 1, 2011 21:27
-
-
Save rboyd/1331965 to your computer and use it in GitHub Desktop.
Detect iPhone user agent, offer app download, and javascript redirect to iTunes App Store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OFFER = 'We have an app available in the App Store! Download now?' | |
ITUNES_URL = '<Your iTunes URL Here>' | |
createCookie = (name,value,days) -> | |
if days | |
date = new Date() | |
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 365)) | |
expires = '; expires=' + date.toGMTString() | |
else | |
expires = '' | |
document.cookie = name + '=' + value + expires + '; path=/'; | |
readCookie = (name) -> | |
nameEQ = name + '=' | |
cookie_array = document.cookie.split(';') | |
for value in cookie_array | |
value = value.substring(1, value.length) while (value.charAt(0) == ' ') | |
return value.substring(nameEQ.length, value.length) if value.indexOf(nameEQ) == 0 | |
$ -> | |
if navigator.userAgent.match(/iPhone/i) or navigator.userAgent.match(/iPod/i) or navigator.userAgent.match(/iPad/i) | |
if !readCookie('iphoneAdvertised') | |
createCookie('iphoneAdvertised', true, 7) | |
res = confirm OFFER | |
if res | |
window.location.replace(ITUNES_URL) |
=) A little better than the original, but if we're going to optimize it to death you could still DRY it out a little more with something like (untested):
userAgentCheck(ios_list) ->
for ios_agent in ios_agent_list
return true if navigator.userAgent.match(ios_agent)
false
$ ->
if userAgentCheck([/iPod/i, /iPhone/i, /iPad/i])
if !readCookie('iphoneAdvertised')
createCookie('iphoneAdvertised', true, 7)
res = confirm OFFER
window.location.replace(ITUNES_URL) if res
I don't know if it makes sense to pass navigator.userAgent since it's accessible from anywhere.
True, good point there. Haven't done any work with detecting / responding
to mobile user agent strings so my ideas may not be worth much.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bobby, any thoughts on my changes below?