问题
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:
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
回答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:
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.
来源:https://stackoverflow.com/questions/51816498/how-to-detect-platform-using-ionic-4