Cordova Demo - Viewing all Contacts

A quick demo of something I’ve wanted to see myself for a while now - a user on Stackoverflow asked if it was possible to view all the contacts on a device using PhoneGap/Cordova. It is rather trivial to do so. Simply perform a search and skip providing an actual filter. Here is an example.

document.addEventListener("deviceready", init, false);
function init() {

	navigator.contacts.find(
		[navigator.contacts.fieldType.displayName],
		gotContacts,
		errorHandler);

}

function errorHandler(e) {
	console.log("errorHandler: "+e);
}

function gotContacts(c) {
	console.log("gotContacts, number of results "+c.length);
	for(var i=0, len=c.length; i<len; i++) {
		console.dir(c[i]);
	}
}

All I’ve done here is run the find method of the Contacts plugin. You must provide the first argument, which specifies which fields you will search against, but you do not have to actually provide a search value. Running this code as is will return the entire contact object, but obviously you could, and should, ask for a subset of the contacts if you only care about particular values.

I tested it on my Android phone and it worked really darn fast, despite having 400+ contacts. Here is the result being viewed via GapDebug:

GapDebug

Not really rocket science, but maybe useful. If you want to copy this code into your own project, you can find it here: https://github.com/cfjedimaster/Cordova-Examples/tree/master/stealcontacts.

Ok, I was about to post this as is, but then I thought, let me add something fun. I modified the code slightly to see if a contact photo exists - and if so - append it to the DOM:

function gotContacts(c) {
	console.log("gotContacts, number of results "+c.length);
	picDiv = document.querySelector("#pictures");
	for(var i=0, len=c.length; i<len; i++) {
		console.dir(c[i]);
		if(c[i].photos && c[i].photos.length > 0) {
			picDiv.innerHTML += "<img src='"+c[i].photos[0].value+"'>";
		}
	}
}

A simple little tweak, but with a fun result: device-2014-12-23-074946

Enjoy!

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