How to tell if a Cordova application is running in the simulator

Just a quick note here but the most recent plugins release included a cool little update to the Device plugin. If you’ve never used it before, the plugin provides basic information about the app’s current working environment, including operating system and device model. In the most recent version, a new property was added: isVirtual.

As you can probably guess, this property will tell you if you’re running on a simulator or a real device. Now while I wouldn’t recommend shipping code that uses this normally, during testing it could be real useful. As an example, here is code that simply toggles what kind of camera should be used - the device camera or the photo gallery:


var sourceType = device.isVirtual ? Camera.PictureSourceType.PHOTOLIBRARY:Camera.PictureSourceType.CAMERA;
	
navigator.camera.getPicture(picDone, picFail, {
	sourceType: sourceType,
	destinationType:Camera.DestinationType.FILE_URI
});

Not rocket science, but useful. Just to be complete, here is a screen shot of the same code running on my device and simulator.

shot2

And if you want, you can grab the source for this demo here: https://github.com/cfjedimaster/Cordova-Examples/tree/master/checkforsim.

For folks curious, running this on Genymotion actually shows that it is considered a simulator, not a real device, even though you run it from the command line like a real device. Surprising.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments