Search code examples
javascripttypescriptuser-agent

Detecting useragent works for android but not iphone?


Goal: Detect if user is on iPhone/iPad/Android (mobile device) and run some code based on that condition

Problem/What happens: It seems to detect android, but doesn't detect iPhone/iPod.

What I've tried: I am testing this with Chrome devtools. I select user agent from Chrome Devtools to something like: Chrome - iPhone , or Chrome - Android Mobile.

user agent iPhone

I've tried debugging this, and I get: uagent = "mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko) version/9.0 mobile/13b137 safari/601.1"

Yet it completely skips the condition

I've also looked at different articles and my match condition looks like it is correct. In fact I got this one from a SO article. But it looks the same on W3Schools, mozilla documentation, etc. I also tried moving the code back out of the service method and into the component itself but that did not help. I remember testing this and it working at a certain point(with iPhone as useragent) but not sure what has changed.

Angular/TypeScript:

this.isMobile = this.securityService.isUserAgentMobile();

isUserAgentMobile(): boolean {
        var isMobile = false;
        var uagent = navigator.userAgent.toLowerCase();
        if (uagent.match(/iPad|iPhone|android/)) {
            console.log("user agent is mobile!");
            isMobile = true;
        }
        return isMobile;
}

Solution

  • Since its set to lowercase, the match has to be lowercase as well:

    var uagent = navigator.userAgent.toLowerCase();
    if (uagent.match(/ipad|iphone|android/))