cordova-plugin-contacts
cordova-plugin-contacts
cordova-plugin-contacts

!! UPDATE: This plugin might deprecated

Hello friend,

This lesson, I’m going to teach you how to access your device contacts using 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

This lesson, I’m going to teach every aspects of cordova contacts plugin. for that, lets create new Cordova (PhoneGap) project

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 New contact ?

Let’s create 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 save your created contact with 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 for 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

Sundaravel M

About the author: Hi! I'm Sundaravel (codesundar), Founder of codesundar.com. I have been a Web, Mobile App developer, Author, and Teacher since 2014. I also worked as a software consultant for fortune 500 companies. I created codesundar.com to share my real-time knowledge in various technologies such as PhoneGap, Ionic, Flutter and more.