Search code examples
capacitor

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


In Cordova you had immediate access to process.env.CORDOVA_PLATFORM is there something similar in Capacitor?

I'm looking to conditionally load some functions on startup and don’t want to block rendering waiting for async Device.getInfo to come back.

For example I want to determine immediately wether to import a script that make's native keyboard modifications, but I don't want to import this script if we are running on web

try {
  const { Keyboard } = Plugins
  Keyboard.setAccessoryBarVisible({ isVisible: true })
} catch (error) {
  // Keyboard isn't available on web so we need to swallow the error
}

I'm using vue-cli


Solution

  • 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 (deprecated)

    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