2016-11-08 84 views
0

我无法在文档中找到哪些是在Ionic 2应用程序中知道它是否在浏览器中运行的最佳方法(使用离子的服务于命令)或设备/仿真器中。Ionic 2:检查是否在浏览器环境中运行的最佳方法

其实我正在做的是检查窗口对象是否有'插件'属性,但我不知道是否有最好的方法。

if(!window['plugins']) { 
//browser 
} 
+0

[如何检测我是否在浏览器(本地开发)在离子2]可能的重复](http://stackoverflow.com/questions/38470325/how-to-detect-if-i-am-in- browser-local-development-in-ionic-2) – hanzo2001

回答

1

哦,我在文档中找到了Platform对象,它有一些方法。 http://ionicframework.com/docs/v2/api/platform/Platform/ 一个是为(键),可以匹配

import { Platform } from 'ionic-angular'; 

@Component({...}) 
export MyPage { 
    constructor(platform: Platform) { 
    this.platform = platform; 
    ... 
    if(this.platform.is('core')) { 
    //it's in the browser 
    } 
    } 
} 
+1

这不是答案。虽然这将在“正常”浏览窗口中运行,但只要您打开开发工具并使用设备工具栏,ionic就会认为您是手机。我还没有找到正确的答案。 – Coo

0

只是为了增加一点上面给出的解决方案,以下似乎就ok工作:

import { Platform } from 'ionic-angular'; 

@IonicPage() 
@Component({}) 
export class WhichPlatformPage { 
    isApp: boolean; 

    constructor(private platform: Platform) { 
    this.isApp = this.platform.is('core') || this.platform.is('mobileweb') ? false : true; 
    } 
} 

ionViewDidLoad() { 
    console.log(this.isApp ? 'Running from mobile' : 'Running from the browser'); 
} 

这似乎为我工作得很好 - 与以前的答案不同的是,我们也在检查'mobileweb'平台。有趣的是,如果您使用的是ionic cordova build browser命令,'mobileweb'会变成'mobile' - 打破这个解决方案 - 因为它试图模拟尽可能多的在设备上。这是提出了如下GitHub上的问题:

https://github.com/ionic-team/ionic/issues/11557

溶液给出以下设置的isApp

this.isApp = !document.URL.startsWith('http');

这工作,因为移动应用开始他们与网页'文件'协议。然而,如果你读到这个问题,Ionic实际上建议不要使用当前的cordova浏览器平台,所以你最好用原来的解决方案。

相关问题