4 Ways to detect Phonegap in a browser or App

I’ve been working with phonegap for years now and one of the great features is being able to develop and test in a browser before pushing the code over to an app. For us web developers, it doesn’t disrupt our normal workflow very much and makes coding apps incredibly easy !

For some reason though, it was very difficult to figure out how to detect if phonegap was running in a browser or on a device. I answered this question on stackoverflow at one point and figured I’d discuss a few alternatives in this post.

Solution #1

My original solution was to use the following:

if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
  document.addEventListener("deviceready", onDeviceReady, false);
} else {
  onDeviceReady(); //this is the browser
}

Solution #2

var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1;
if ( app ) {
    // PhoneGap application
} else {
    // Web page
}  

Solution #3

If you’re running a newer version say 1.7 you could try this chunk of code to detect if phonegap is running:

if (window.cordova) {
  //do stuff
}

Solution #4

I’ve never had much luck with this one, but since it’s straight out of the documentation why not give it a go if the above solutions are not enough 🙂

if (PhoneGap.available){ //do things }

There you have it folks! Hopefully this saves you hours of trying to figure it out on your own.

Leave a Reply

Your email address will not be published. Required fields are marked *