Anuj Batwe
Anuj Batwe

Reputation: 35

Cordova/jQuery - Identifying whether your app is being run on Web/Mobile browser or mobile app (Android/iOS)

I develop apps for Android/iOS using Cordova/Phonegap. I generally use a single code base for my web and mobile content. I use a SQLite database and/or other native plugins when it is a mobile app and have to avoid those LOCs when I'm on web.

But I'm facing a problem identifying whether my app is being run on a web browser on Desktop/Mac/Android/iOS or as a mobile app (Android/iOS).

I have tried userAgent sniffing, but this regex technique fails especially when running the code on mobile browsers. Following is the code I used to identify OS and version of the device:

getOSAndVersion: function() {
        var that = this;
        var userOS;    // will either be iOS, Android or unknown
        var userOSver; // this is a string, used to denote OS version
        var ua = navigator.userAgent;
        var uaindex;

        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua)) {
            window.deviceType = "Mobile";                                  
        } else {
            window.deviceType = "Web";                    
        }

        // determine OS
        if (ua.match(/iPad/i) || ua.match(/iPhone/i)) {
            userOS = 'iOS';
            uaindex = ua.indexOf('OS ');
        }
        else if (ua.match(/Android/i)) {
            userOS = 'Android';
            uaindex = ua.indexOf('Android ');
        }
        else {
            userOS = 'unknown';
        }

        // determine version
        if (userOS === 'iOS' && uaindex > -1) {
            userOSver = ua.substr(uaindex + 3, 3).replace('_', '.');
        }
        else if (userOS === 'Android' && uaindex > -1) {
            userOSver = ua.substr(uaindex + 8, 3);
        }
        else {
            userOSver = 'unknown';
        }
        return { osVersion: userOSver, os: userOS, deviceType: window.deviceType };
    }

Is there any other technique I can use to reliably identify where my code is being run?

P.S. : I'm averse to using any other Cordova/JS plugin to identify it but still open for discussion.

Upvotes: 0

Views: 526

Answers (2)

Simon Prickett
Simon Prickett

Reputation: 4148

You could just check if cordova is defined?

if (cordova) {
    // Running in your app
} else {
    // Not running in your app, so website
}

Upvotes: 0

KOTIOS
KOTIOS

Reputation: 11194

In Cordova when app is runing into app the url is prefixed by file:// and when running in mobile browser the url is prefixed with http or https protocal.

Solution :

  1. Get url of you current page (check this)
  2. Identify its prefix if file:// the its app
  3. If http or https then mobile browser

Upvotes: 1

Related Questions