How to detect platform using Ionic 4

前端 未结 8 1032
慢半拍i
慢半拍i 2021-02-09 08:24

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.

<
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 08:45

    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';
        }
      }
    }
    

提交回复
热议问题