How to detect platform using Ionic 4

2020-06-21 05:49发布

问题:

How to detect browser and mobileweb platform using Ionic 4 because when I tried with below code in desktop browser it is not falling in ‘core’ condition.

if (this.platform.is('core')) {
    alert('core platform');
  } else {
    alert('something else');
  }

When I have debug in chrome developer tool it showing 'android' platform as per below snapshot.

Can anyone please help me how to detect platform in Ionic 4 or what can be the alternative for this?

回答1:

The following link may help you:
https://forum.ionicframework.com/t/how-to-determine-if-browser-or-app/89149/16

or you can use the following method:

public isDesktop() {
    let platforms = this.plt.platforms();
    if(platforms[0] == "core" || platforms[0] == "mobileweb") {
        return true;
    } else {
        return false;
    }
}


回答2:

Currently Ionic 4 has support for platform detection. The following code works for me.

import { Platform } from '@ionic/angular';
...
constructor(private platform: Platform) {}
...
ngOnInit() {
   this.platform.ready().then(() => {
      if (this.platform.is('android')) {
           console.log('android');
      } else if (this.platform.is('ios')) {
           console.log('ios');
      } else {
           //fallback to browser APIs or
           console.log('The platform is not supported');
             }
      }}


回答3:

For my use case I wanted something to distinguish between native and browser platforms. That is, is my app running in a browser or a native mobile device. Here's the service I came up with:

import { Injectable } from '@angular/core';
import {Platform} from '@ionic/angular';


type CurrentPlatform = 'browser' | 'native';

@Injectable({
  providedIn: 'root'
})
export class CurrentPlatformService {

  private _currentPlatform: CurrentPlatform;

  constructor(private platform: Platform) {
    this.setCurrentPlatform();
  }

  get currentPlatform() {
    return this._currentPlatform;
  }

  isNative() {
    return this._currentPlatform === 'native';
  }
  isBrowser() {
    return this._currentPlatform === 'browser';
  }

  private setCurrentPlatform() {
    // Are we on mobile platform? Yes if platform is ios or android, but not desktop or mobileweb, no otherwise
    if (
        this.platform.is('ios')
        || this.platform.is('android')
        && !( this.platform.is('desktop') || this.platform.is('mobileweb') ) ) {
      this._currentPlatform = 'mobile';
    } else {
      this._currentPlatform = 'browser';
    }
  }
}


回答4:

Ionic-4 Platform specific value

goto- node_modules@ionic\angular\dist\providers\platform.d.ts

Platform Name | Description |

 * | android         | on a device running Android.       |
 * | cordova         | on a device running Cordova.       |
 * | ios             | on a device running iOS.           |
 * | ipad            | on an iPad device.                 |
 * | iphone          | on an iPhone device.               |
 * | phablet         | on a phablet device.               |
 * | tablet          | on a tablet device.                |
 * | electron        | in Electron on a desktop device.   |
 * | pwa             | as a PWA app.   |
 * | mobile          | on a mobile device.                |
 * | desktop         | on a desktop device.               |
 * | hybrid          | is a cordova or capacitor app.     |


回答5:

The logic used by you is the correct logic.

The issue is with the ionic 4 and it is returning wrong values.

Bug has been posted on ionic repo: https://github.com/ionic-team/ionic/issues/15165

The other issue related to platform coming as ['android'] is also a bug and that has also been reported here: https://github.com/ionic-team/ionic/issues/15051



回答6:

For detecting the web platform you should use Bowser . I have used this in ionic 4 for detecting browser platform i.e whether it is safari or chrome.

Step 1 : You need to install bowser in your project

npm install bowser@2.7.0 --save-exact

Step 2 : Then you need to import it in .ts page where you want to use it. let suppose home.ts

import Bowser from "bowser";

Step 3 : Then you need to write login to check browser platform inside a function in home.ts

checkBrowserPlatform() {
  const browser = Bowser.getParser(window.navigator.userAgent);
  const browserName = browser.getBrowserName();
    console.log(browserName);
  }

By calling checkBrowserPlatform() you can know the current browser name.



回答7:

Ionic 4 / Capacitor

I have written a service like so:

detect-platform.service.ts

import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { find } from 'lodash';

@Injectable({
    providedIn: 'root'
})
export class DetectPlatformService {

    isDevice: boolean = false;

    constructor(
        private platform: Platform, ) { }

    setPlatform(): void {

        const platforms: string[] = this.platform.platforms();
        const platform: string = find(platforms, (p: string) => {
            return p === 'capacitor';
        });

        this.isDevice = platform ? true : false;
    }   

}

Note: Since I use Ionic 4/Capacitor it gives true if it is on device else false.



回答8:

In case anyone is still struggling with this on ionic4/cordova, I solved it using

import {Device} from '@ionic-native/device/ngx'

Just add it into your app.modules and run this.device.platform wherever you need to find out, to give an idea, the output on web and apk from this simple code

console.log(this.platform.platforms());
console.log(this.device.platform);

is this:

Running on web (desktop and mobile)
["android", "phablet", "cordova", "mobile", "hybrid"]
browser

Running android local (apk)
["android", "cordova", "desktop", "hybrid"]
Android

Now I can correctly use the plugins for browser or mobile correctly, in my case is image loading and cropping.

A full explanation can be found at https://www.damirscorner.com/blog/posts/20171124-DetectingWhereIonicAppIsRunning.html