Skip to content

Instantly share code, notes, and snippets.

@rboyd
Created November 1, 2011 21:27
Show Gist options
  • Save rboyd/1331965 to your computer and use it in GitHub Desktop.
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
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)
@caleywoods
Copy link

Bobby, any thoughts on my changes below?

userAgentCheck (userAgent) ->
  if userAgent.match(/iPhone/i) or userAgent.match(/iPod/i) or userAgent.match(/iPad/i)
    return true
  else
    return false
$ -> 
  if userAgentCheck(navigator.userAgent)
    if !readCookie('iphoneAdvertised')
      createCookie('iphoneAdvertised', true, 7)
      res = confirm OFFER
      window.location.replace(ITUNES_URL) if res

@rboyd
Copy link
Author

rboyd commented Nov 2, 2011

=) 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.

@caleywoods
Copy link

caleywoods commented Nov 2, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment