How can I determine if the current platform is a native app or web in Capacitor?

The answers so far are all correct, if you take a look into the Capacitors source code, there a few ways available, which can be used (but are undocumented for now):

  • Capacitor.getPlatform(); // -> 'web', 'ios' or 'android'
  • Capacitor.platform // -> 'web', 'ios' or 'android' (deprecated)
  • Capacitor.isNative // -> true or false

Be aware, that the method Capacitor.isPluginAvailable('PluginName'); only returns if the plugins is available or not (obviously) but important here, it does not tell you, if the method you want to execute after checking the availability is for your platform available.

The documentation of the Capacitor Plugins is not completed (yet).

Example (code), for the plugin StatusBar:

// Native StatusBar Plugin available
if (Capacitor.isPluginAvailable('StatusBar')) {

    // Tint statusbar color
    StatusBar.setBackgroundColor({
        color: '#FF0000'
    });

}

This would result in an error on iOS, since this method is not available there, on Android it works fine so far.

That means, that you need to implement a check of the Plugin and Platform combination by yourself (for now), may this will be improved in the future by Ionic / Capacitor itself.

Something like:

// Native StatusBar available
if (Capacitor.getPlatform() === 'android' && Capacitor.isPluginAvailable('StatusBar')) {

    // Tint statusbar color
    StatusBar.setBackgroundColor({
        color: this.config.module.GYMY_MODAL_STATUSBAR_HEX_STRING
    });

}

One more thing, you are not able to check, whether the method exists within this plugin (f. e. for the code above setBackgroundColor) as it is available, but throws an error (Error: not implemented) on a platform, which does not support it.

Hope I could help some of you guys.

Cheers Unkn0wn0x


As of Capacitor 3, you can use the following method to determine if it's running on a native device ("iOS" - "Android") or not ("web").

import { Capacitor } from '@capacitor/core';
if(Capacitor.isNativePlatform()) {
    // Platform is mobile
} else {
    // Platform is not mobile
}

Official documentation link. https://capacitorjs.com/docs/core-apis/web#isnativeplatform


There is also the property Capacitor.isNative which you could use to determine whether the WebApp is running in Capacitor or in the Web.

https://github.com/ionic-team/capacitor/blob/master/core/src/definitions.ts

Update: In Capacitor V3 you can use Capacitor.isNativePlatform() for this. https://capacitorjs.com/docs/v3/core-apis/web#isnativeplatform


Found it undocumented: Capacitor.platform

Capacitor.platform could be for example web ios android

Also if you wanted to know if you were running native before loading Capacitor, i.e you wanted to reduce bundle size by not including Capacitor on the web.

window.origin.includes('capacitor://')

Tags:

Capacitor