cordova-plugin-contacts tutorial (Accessing device contacts)

cordova-contacts-plugin-tutorial

Cordova Plugin Contacts Tutorial

This lesson, I'm going to teach you how to access your device contacts using https://github.com/apache/cordova-plugin-contacts by using this plugin you can create a new contact, or search contact or even you can pick your contacts (using contact picker), but you can't edit or delete existing contact using this plugin.

New to PhoneGap (Cordova)? Visit https://codesundar.com/phonegap-tutorial/

Getting Started

Let's create a new project and add required platforms and plugins

    cordova create contactsexample com.codesundar.contactexample contactsexample
    cd contactsexample
    cordova platform add android
    cordova plugin add cordova-plugin-contacts

Methods

  • navigator.contacts.create
  • navigator.contacts.find
  • navigator.contacts.pickContact

How to create a new contact?

Let's create a new contact using this plugin.to create new contact we can use navigator.contacts.create() function.

Syntax

function createContact() {
var myContact = navigator.contacts.create({

    displayName: 'CODESUNDAR',
    phoneNumbers: [{
        "type": "mobile",
        "value": "+919952313535"
    }
    ]

}); 
myContact.save(); 
}

navigator.contacts.create used for creating new contacts, you need to pass JSON objects inside the function, .save() used for saving your created contact with the device

Search contact?

navigator.contacts.find(fields, onSuccess, onError, options);

navigator.contacts.find() used for search contact with given field names

Example

    function searchContact() {
        var keyword = document.getElementById('keyword').value;
        console.log(keyword);
    
        var options = new ContactFindOptions();
        options.filter = keyword;
        options.multiple = true;
        options.desiredFields = [navigator.contacts.fieldType.id];
        options.hasPhoneNumber = true;
        var fields = [navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.name];
        navigator.contacts.find(fields, function (res) {
            console.log(res);
            console.log('Found', res.length);
            alert('Found, ')
        }, function (err) {
            console.log('Error', err);
        }, options);
    }

Pick Contact

navigator.contacts.pickContact used to open a contact picker, where you can pick for particular contact & retrieve information about the contact

    function openContactPicker() {
        navigator.contacts.pickContact(function(contact) {
            alert(JSON.stringify(contact))
        }, function(err) {
            console.log('Error: ' + err);
        });
    }

Cheers!

Feel free to comment below, if you faced any issues