1

I'm trying to use the following script to detect whether the browser is iOS 5 or higher (from this SO thread Detect iOS version less than 5 with JavaScript).

function iOSversion() {
    if (/iP(hone|od|ad)/.test(navigator.platform)) {
        var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
        return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
    }
}

ver = iOSversion();

if (ver[0] >= 5) {
    alert('This is running iOS 5 or later.');
} else {
    alert('This is NOT running iOS 5 or later.');
}

It works in iOS 5 or later as it should, but in any other browser it produces the following error:

Uncaught TypeError: Cannot read property '0' of undefined 

And then all JavaScript below this script fails.

Please can someone advise how I can fix this?? Thank you.

Community
  • 1
  • 1
user2586455
  • 511
  • 2
  • 6
  • 16

2 Answers2

5

You're checking if ver[0] >= 5, but if it's not iOS, ver is undefined, so you have to check if it's defined first :

function iOSversion() {
    if (/iP(hone|od|ad)/.test(navigator.platform)) {
        var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
        return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
    }
}

var ver = iOSversion();

if (ver && ver[0] >= 5) {
    alert('This is running iOS 5 or later.');
} else {
    alert('This is NOT running iOS 5 or later.');
}
adeneo
  • 293,187
  • 26
  • 361
  • 361
  • May be a better idea to `typeof ver != 'undefined'` instead of rely on `if (ver)` – Luqmaan Aug 02 '13 at 14:32
  • Perfect, thank you! I knew it was something simple I was missing. I'm using this to apply position: fixed to mobile browsers that can handle it. UA sniffing is necessary over feature detection in this case as most mobile browsers support fixed position but many in a very buggy way. Thanks again for the speedy answer. – user2586455 Aug 02 '13 at 14:37
0

iOSversion() returns undefined for any other browser.

Trying to do: undefined[0] will give you the error that you got.

You can change your check to:

if (ver !== undefined && ver[0] >= 5) {
    // ..
}
Halcyon
  • 54,624
  • 10
  • 83
  • 122