如何区分PhoneGap应用程序和本机浏览器?

时间:2012-03-03 11:35:36

标签: javascript android cordova

为了加快开发速度,我们的团队已经习惯直接在Chrome中测试我们的大部分手机屏幕实现(因为它几乎都是Javascript)。但是我们想要在Phonegap提供的ondeviceready回调中运行某些代码(或者只是在浏览器中的document.ready上)。如果我们想在两种情况下调用不同的代码,我们如何区分这两种情况?

2 个答案:

答案 0 :(得分:1)

我们采用相同的方法并遇到同样的问题。以下是我们为Android解决的问题(应该与WebKit浏览器一起使用,也可以在iOS上使用)。

这个想法是:

  • 创建一个表示PhoneGap处于活动状态的Java类。
  • 将其添加到浏览器中的全局对象列表中。
  • 编写一个封装检查的JavaScript包装器。

现在有些代码。

Java类:

public class MyPhoneGap {

    public boolean isActive() {
        return true;
    }
}

使用浏览器注册此类的实例:

public class MyActivity extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setIntegerProperty("splashscreen", R.drawable.splash);
        super.loadUrl("file:///android_asset/www/index.html");
        this.appView.getSettings().setJavaScriptEnabled(true);
        this.appView.addJavascriptInterface(new MyPhoneGap(), "MyPhoneGap");
    }
}

JavaScript包装器:

My.PhoneGap = {
    active : null,
    isActive : function() {
        if (!My.Util.Type.isBoolean(My.PhoneGap.active)) {
            if (My.Util.Type.exists(window.MyPhoneGap)) {
                if (window.MyPhoneGap.isActive()) {
                    My.PhoneGap.active = true;
                } else {
                    My.PhoneGap.active = false;
                }
            } else {
                My.PhoneGap.active = false;
            }
        }
        return My.PhoneGap.active;
    }
};

用法:

if (My.PhoneGap.isActive()) {
    // Rely on PhoneGap APIs
} else {
    // Use some mock/default/dummy impl
}

最后一件事:在Chrome中开发/测试非常方便,但请在真实设备上进行测试。性能/ API可靠性的差异非常不同。

答案 1 :(得分:1)

您可以查看JavaScript中是否未定义设备

/* are we running on device or in a browser? */                                                                                              
this.isDevice = (typeof(device) != 'undefined');

/* if the device is not defined we assume we in a browser */
if(!this.isDevice) {
    ... browser code here ...
}
相关问题