1

Hi I am running into issues with browser detection and cookies. I am wanting to have a message display to iPhone or Android users accessing my site with a "do not show me again" check box. I cant use PHP or Jquery so I have to stick with strait javascript. I need to following events to happen:

if Android
and
if Cookie has not been set display message
else do nothing

I am new to coding so any help would be much appreciated.

Dave
  • 13
  • 2

2 Answers2

0

You can use the cookies, but web storage is easier to use. Older browsers (IE7 and opera mini) may not support web storage, but both iOS safari and Android browser do.

Concerning browser detection (you should use feature detection), the navigator object stores several useful attributes, namely userAgent and platform. appName is also available, but it doesn't seem useful (Chrome 23 reports "Netscape").

Inferring much from the user agent is a tricky business, but

  • The Android default browser reports "Android" in its user agent (ref.)
  • For iOS, it seems sufficient to detect "iPad" and "iPhone" in the user agent (ref.)

Try:

if(window.localStorage
  && !localStorage.getItem("dialogShown")
  && /Android|iPad|iPhone/.test(navigator.userAgent)
){
  // show the dialog (unhide an element)
}

when the dialog is dismissed:

var checkbox /* = document.getElementById(...) */;

if(checkbox.checked){
  localStorage.setItem("dialogShown",true);
}
John Dvorak
  • 26,799
  • 13
  • 69
  • 83
0

So you have two things to accomplish:

1st - Browser Detecttion

Browser detection via javascript is tricky thing to do, I recommend for you to take a look at this post to understand it.

You have to catch Android and iPhone browsers and both of them have the "mobile" string in theirs user agent (like all decent mobile browsers), so you can do it with a function like:

function isMobile() {
    return (/mobile/i).test(window.navigator.userAgent);
}

This function will return true, when in a mobile browser.

Take a look at this question for alternative approaches.

2nd - Cookie Access

The cookie "API" is an even worse interface. To deal with it you have to write your key=value data to document.cookie (read the MDN's documentation).

So, if you want to store on cookies the user preference, you can do something like:

document.cookie = "skip_message=1"

As I said, the cookie API interface can be very tricky sometimes so you should use a 3rd party library to read an write cookies. The little framework in the MDN documentation is a good one.

Your target browsers have more advanced features, so if you don't need to suport older browser I would recommend you to use localStorage

Community
  • 1
  • 1
Renan Ivo
  • 1,368
  • 9
  • 17