-

- -

Wednesday, October 7, 2015

Cordova Plugin Contacts

.

cordova-plugin-contacts

This plugin defines a global navigator.contacts object, which provides access to the device contacts database.
Although the object is attached to the global scoped navigator, it is not available until after thedeviceready event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    console.log(navigator.contacts);
}
WARNING: Collection and use of contact data raises important privacy issues. Your app's privacy policy should discuss how the app uses contact data and whether it is shared with any other parties. Contact information is considered sensitive because it reveals the people with whom a person communicates. Therefore, in addition to the app's privacy policy, you should strongly consider providing a just-in-time notice before the app accesses or uses contact data, if the device operating system doesn't do so already. That notice should provide the same information noted above, as well as obtaining the user's permission (e.g., by presenting choices for OK and No Thanks). Note that some app marketplaces may require the app to provide a just-in-time notice and obtain the user's permission before accessing contact data. A clear and easy-to-understand user experience surrounding the use of contact data helps avoid user confusion and perceived misuse of contact data. For more information, please see the Privacy Guide.
:warning: Report issues on the Apache Cordova issue tracker

Installation

This requires cordova 5.0+ ( current stable v1.0.0 )
cordova plugin add cordova-plugin-contacts
Older versions of cordova can still install via the deprecated id ( stale v0.2.16 )
cordova plugin add org.apache.cordova.contacts
It is also possible to install via repo url directly ( unstable )
cordova plugin add https://github.com/apache/cordova-plugin-contacts.git

Firefox OS Quirks

Create www/manifest.webapp as described in Manifest Docs. Add relevant permisions. There is also a need to change the webapp type to "privileged" - Manifest DocsWARNING: All privileged apps enforce Content Security Policy which forbids inline script. Initialize your application in another way.
"type": "privileged",
"permissions": {
    "contacts": {
        "access": "readwrite",
        "description": "Describe why there is a need for such permission"
    }
}

Windows Quirks

Prior to Windows 10: Any contacts returned from find and pickContact methods are readonly, so your application cannot modify them. find method available only on Windows Phone 8.1 devices.
Windows 10 and above: Contacts may be saved and will be saved to app-local contacts storage. Contacts may also be deleted.

Windows 8 Quirks

Windows 8 Contacts are readonly. Via the Cordova API Contacts are not queryable/searchable, you should inform the user to pick a contact as a call to contacts.pickContact which will open the 'People' app where the user must choose a contact. Any contacts returned are readonly, so your application cannot modify them.

navigator.contacts

Methods

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

Objects

  • Contact
  • ContactName
  • ContactField
  • ContactAddress
  • ContactOrganization
  • ContactFindOptions
  • ContactError
  • ContactFieldType

navigator.contacts.create

The navigator.contacts.create method is synchronous, and returns a new Contact object.
This method does not retain the Contact object in the device contacts database, for which you need to invoke the Contact.save method.

Supported Platforms

  • Android
  • BlackBerry 10
  • Firefox OS
  • iOS
  • Windows Phone 8

Example

var myContact = navigator.contacts.create({"displayName": "Test User"});

navigator.contacts.find

The navigator.contacts.find method executes asynchronously, querying the device contacts database and returning an array of Contact objects. The resulting objects are passed to thecontactSuccess callback function specified by the contactSuccess parameter.
The contactFields parameter specifies the fields to be used as a search qualifier. A zero-lengthcontactFields parameter is invalid and results in ContactError.INVALID_ARGUMENT_ERROR. AcontactFields value of "*" searches all contact fields.
The contactFindOptions.filter string can be used as a search filter when querying the contacts database. If provided, a case-insensitive, partial value match is applied to each field specified in thecontactFields parameter. If there's a match for any of the specified fields, the contact is returned. Use contactFindOptions.desiredFields parameter to control which contact properties must be returned back.

Parameters

  • contactFields: Contact fields to use as a search qualifier. (DOMString[]) [Required]
  • contactSuccess: Success callback function invoked with the array of Contact objects returned from the database. [Required]
  • contactError: Error callback function, invoked when an error occurs. [Optional]
  • contactFindOptions: Search options to filter navigator.contacts. [Optional]
    Keys include:
    • filter: The search string used to find navigator.contacts. (DOMString) (Default: "")
    • multiple: Determines if the find operation returns multiple navigator.contacts. (Boolean)(Default: false)
    • desiredFields: Contact fields to be returned back. If specified, the resulting Contact object only features values for these fields. (DOMString[]) [Optional]
    • hasPhoneNumber(Android only): Filters the search to only return contacts with a phone number informed. (Boolean) (Default: false)

Supported Platforms

  • Android
  • BlackBerry 10
  • Firefox OS
  • iOS
  • Windows Phone 8
  • Windows (Windows Phone 8.1 and Windows 10)

Example

function onSuccess(contacts) {
    alert('Found ' + contacts.length + ' contacts.');
};

function onError(contactError) {
    alert('onError!');
};

// find all contacts with 'Bob' in any name field
var options      = new ContactFindOptions();
options.filter   = "Bob";
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, onSuccess, onError, options);

Windows Quirks

  • __contactFields__ is not supported and will be ignored. find method will always attempt to match the name, email address, or phone number of a contact.

navigator.contacts.pickContact

The navigator.contacts.pickContact method launches the Contact Picker to select a single contact. The resulting object is passed to the contactSuccess callback function specified by thecontactSuccess parameter.

Parameters

  • contactSuccess: Success callback function invoked with the single Contact object. [Required]
  • contactError: Error callback function, invoked when an error occurs. [Optional]

Supported Platforms

  • Android
  • iOS
  • Windows Phone 8
  • Windows 8
  • Windows

Example

navigator.contacts.pickContact(function(contact){
        console.log('The following contact has been selected:' + JSON.stringify(contact));
    },function(err){
        console.log('Error: ' + err);
    });

Contact

The Contact object represents a user's contact. Contacts can be created, stored, or removed from the device contacts database. Contacts can also be retrieved (individually or in bulk) from the database by invoking the navigator.contacts.find method.
NOTE: Not all of the contact fields listed above are supported on every device platform. Please check each platform's Quirks section for details.

Properties

  • id: A globally unique identifier. (DOMString)
  • displayName: The name of this Contact, suitable for display to end users. (DOMString)
  • name: An object containing all components of a persons name. (ContactName)
  • nickname: A casual name by which to address the contact. (DOMString)
  • phoneNumbers: An array of all the contact's phone numbers. (ContactField[])
  • emails: An array of all the contact's email addresses. (ContactField[])
  • addresses: An array of all the contact's addresses. (ContactAddress[])
  • ims: An array of all the contact's IM addresses. (ContactField[])
  • organizations: An array of all the contact's organizations. (ContactOrganization[])
  • birthday: The birthday of the contact. (Date)
  • note: A note about the contact. (DOMString)
  • photos: An array of the contact's photos. (ContactField[])
  • categories: An array of all the user-defined categories associated with the contact.(ContactField[])
  • urls: An array of web pages associated with the contact. (ContactField[])

Methods

  • clone: Returns a new Contact object that is a deep copy of the calling object, with the idproperty set to null.
  • remove: Removes the contact from the device contacts database, otherwise executes an error callback with a ContactError object.
  • save: Saves a new contact to the device contacts database, or updates an existing contact if a contact with the same id already exists.

Supported Platforms

  • Amazon Fire OS
  • Android
  • BlackBerry 10
  • Firefox OS
  • iOS
  • Windows Phone 8
  • Windows 8
  • Windows

Save Example

function onSuccess(contact) {
    alert("Save Success");
};

function onError(contactError) {
    alert("Error = " + contactError.code);
};

// create a new contact object
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber";            // specify both to support all devices

// populate some fields
var name = new ContactName();
name.givenName = "Jane";
name.familyName = "Doe";
contact.name = name;

// save to device
contact.save(onSuccess,onError);

Clone Example

    // clone the contact object
    var clone = contact.clone();
    clone.name.givenName = "John";
    console.log("Original contact name = " + contact.name.givenName);
    console.log("Cloned contact name = " + clone.name.givenName);

Remove Example

function onSuccess() {
    alert("Removal Success");
};

function onError(contactError) {
    alert("Error = " + contactError.code);
};

// remove the contact from the device
contact.remove(onSuccess,onError);

Android 2.X Quirks

  • categories: Not supported on Android 2.X devices, returning null.

BlackBerry 10 Quirks

  • id: Assigned by the device when saving the contact.

FirefoxOS Quirks

  • categories: Partially supported. Fields pref and type are returning null
  • ims: Not supported
  • photos: Not supported

iOS Quirks

  • displayName: Not supported on iOS, returning null unless there is no ContactName specified, in which case it returns the composite name, nickname or "", respectively.
  • birthday: Must be input as a JavaScript Date object, the same way it is returned.
  • photos: Returns a File URL to the image, which is stored in the application's temporary directory. Contents of the temporary directory are removed when the application exits.
  • categories: This property is currently not supported, returning null.

Windows Phone 8 Quirks

  • displayName: When creating a contact, the value provided for the display name parameter differs from the display name retrieved when finding the contact.
  • urls: When creating a contact, users can input and save more than one web address, but only one is available when searching the contact.
  • phoneNumbers: The pref option is not supported. The type is not supported in a find operation. Only one phoneNumber is allowed for each type.
  • emails: The pref option is not supported. Home and personal references same email entry. Only one entry is allowed for each type.
  • addresses: Supports only work, and home/personal type. The home and personal type reference the same address entry. Only one entry is allowed for each type.
  • organizations: Only one is allowed, and does not support the preftype, and departmentattributes.
  • note: Not supported, returning null.
  • ims: Not supported, returning null.
  • birthdays: Not supported, returning null.
  • categories: Not supported, returning null.
  • remove: Method is not supported

Windows Quirks

  • photos: Returns a File URL to the image, which is stored in the application's temporary directory.
  • birthdays: Not supported, returning null.
  • categories: Not supported, returning null.
  • remove: Method is only supported in Windows 10 or above.

ContactAddress

The ContactAddress object stores the properties of a single address of a contact. A Contact object may include more than one address in a ContactAddress[] array.

Properties

  • pref: Set to true if this ContactAddress contains the user's preferred value. (boolean)
  • type: A string indicating what type of field this is, home for example. (DOMString)
  • formatted: The full address formatted for display. (DOMString)
  • streetAddress: The full street address. (DOMString)
  • locality: The city or locality. (DOMString)
  • region: The state or region. (DOMString)
  • postalCode: The zip code or postal code. (DOMString)
  • country: The country name. (DOMString)

Supported Platforms

  • Amazon Fire OS
  • Android
  • BlackBerry 10
  • Firefox OS
  • iOS
  • Windows Phone 8
  • Windows 8
  • Windows

Example

// display the address information for all contacts

function onSuccess(contacts) {
    for (var i = 0; i < contacts.length; i++) {
        for (var j = 0; j < contacts[i].addresses.length; j++) {
            alert("Pref: "         + contacts[i].addresses[j].pref          + "\n" +
                "Type: "           + contacts[i].addresses[j].type          + "\n" +
                "Formatted: "      + contacts[i].addresses[j].formatted     + "\n" +
                "Street Address: " + contacts[i].addresses[j].streetAddress + "\n" +
                "Locality: "       + contacts[i].addresses[j].locality      + "\n" +
                "Region: "         + contacts[i].addresses[j].region        + "\n" +
                "Postal Code: "    + contacts[i].addresses[j].postalCode    + "\n" +
                "Country: "        + contacts[i].addresses[j].country);
        }
    }
};

function onError(contactError) {
    alert('onError!');
};

// find all contacts
var options = new ContactFindOptions();
options.filter = "";
var filter = ["displayName", "addresses"];
navigator.contacts.find(filter, onSuccess, onError, options);

Android 2.X Quirks

  • pref: Not supported, returning false on Android 2.X devices.

BlackBerry 10 Quirks

  • pref: Not supported on BlackBerry devices, returning false.
  • type: Partially supported. Only one each of Work and Home type addresses can be stored per contact.
  • formatted: Partially supported. Returns a concatenation of all BlackBerry address fields.
  • streetAddress: Supported. Returns a concatenation of BlackBerry address1 and address2address fields.
  • locality: Supported. Stored in BlackBerry city address field.
  • region: Supported. Stored in BlackBerry stateProvince address field.
  • postalCode: Supported. Stored in BlackBerry zipPostal address field.
  • country: Supported.

FirefoxOS Quirks

  • formatted: Currently not supported

iOS Quirks

  • pref: Not supported on iOS devices, returning false.
  • formatted: Currently not supported.

Windows 8 Quirks

  • pref: Not supported

Windows Quirks

  • pref: Not supported

ContactError

The ContactError object is returned to the user through the contactError callback function when an error occurs.

Properties

  • code: One of the predefined error codes listed below.

Constants

  • ContactError.UNKNOWN_ERROR (code 0)
  • ContactError.INVALID_ARGUMENT_ERROR (code 1)
  • ContactError.TIMEOUT_ERROR (code 2)
  • ContactError.PENDING_OPERATION_ERROR (code 3)
  • ContactError.IO_ERROR (code 4)
  • ContactError.NOT_SUPPORTED_ERROR (code 5)
  • ContactError.PERMISSION_DENIED_ERROR (code 20)

ContactField

The ContactField object is a reusable component that represents contact fields generically. EachContactField object contains a valuetype, and pref property. A Contact object stores several properties in ContactField[] arrays, such as phone numbers and email addresses.
In most instances, there are no pre-determined values for a ContactField object's type attribute. For example, a phone number can specify type values of homeworkmobileiPhone, or any other value that is supported by a particular device platform's contact database. However, for the Contactphotos field, the type field indicates the format of the returned image: url when the value attribute contains a URL to the photo image, or base64 when the value contains a base64-encoded image string.

Properties

  • type: A string that indicates what type of field this is, home for example. (DOMString)
  • value: The value of the field, such as a phone number or email address. (DOMString)
  • pref: Set to true if this ContactField contains the user's preferred value. (boolean)

Supported Platforms

  • Amazon Fire OS
  • Android
  • BlackBerry 10
  • Firefox OS
  • iOS
  • Windows Phone 8
  • Windows 8
  • Windows

Example

    // create a new contact
    var contact = navigator.contacts.create();

    // store contact phone numbers in ContactField[]
    var phoneNumbers = [];
    phoneNumbers[0] = new ContactField('work', '212-555-1234', false);
    phoneNumbers[1] = new ContactField('mobile', '917-555-5432', true); // preferred number
    phoneNumbers[2] = new ContactField('home', '203-555-7890', false);
    contact.phoneNumbers = phoneNumbers;

    // save the contact
    contact.save();

Android Quirks

  • pref: Not supported, returning false.

BlackBerry 10 Quirks

  • type: Partially supported. Used for phone numbers.
  • value: Supported.
  • pref: Not supported, returning false.

iOS Quirks

  • pref: Not supported, returning false.

Windows8 Quirks

  • pref: Not supported, returning false.

Windows Quirks

  • pref: Not supported, returning false.

ContactName

Contains different kinds of information about a Contact object's name.

Properties

  • formatted: The complete name of the contact. (DOMString)
  • familyName: The contact's family name. (DOMString)
  • givenName: The contact's given name. (DOMString)
  • middleName: The contact's middle name. (DOMString)
  • honorificPrefix: The contact's prefix (example Mr. or Dr.(DOMString)
  • honorificSuffix: The contact's suffix (example Esq.). (DOMString)

Supported Platforms

  • Amazon Fire OS
  • Android
  • BlackBerry 10
  • Firefox OS
  • iOS
  • Windows Phone 8
  • Windows 8
  • Windows

Example

function onSuccess(contacts) {
    for (var i = 0; i < contacts.length; i++) {
        alert("Formatted: "  + contacts[i].name.formatted       + "\n" +
            "Family Name: "  + contacts[i].name.familyName      + "\n" +
            "Given Name: "   + contacts[i].name.givenName       + "\n" +
            "Middle Name: "  + contacts[i].name.middleName      + "\n" +
            "Suffix: "       + contacts[i].name.honorificSuffix + "\n" +
            "Prefix: "       + contacts[i].name.honorificSuffix);
    }
};

function onError(contactError) {
    alert('onError!');
};

var options = new ContactFindOptions();
options.filter = "";
filter = ["displayName", "name"];
navigator.contacts.find(filter, onSuccess, onError, options);

Android Quirks

  • formatted: Partially supported, and read-only. Returns a concatenation of honorificPrefix,givenNamemiddleNamefamilyName, and honorificSuffix.

BlackBerry 10 Quirks

  • formatted: Partially supported. Returns a concatenation of BlackBerry firstName and lastNamefields.
  • familyName: Supported. Stored in BlackBerry lastName field.
  • givenName: Supported. Stored in BlackBerry firstName field.
  • middleName: Not supported, returning null.
  • honorificPrefix: Not supported, returning null.
  • honorificSuffix: Not supported, returning null.

FirefoxOS Quirks

  • formatted: Partially supported, and read-only. Returns a concatenation of honorificPrefix,givenNamemiddleNamefamilyName, and honorificSuffix.

iOS Quirks

  • formatted: Partially supported. Returns iOS Composite Name, but is read-only.

Windows 8 Quirks

  • formatted: This is the only name property, and is identical to displayName, and nickname
  • familyName: not supported
  • givenName: not supported
  • middleName: not supported
  • honorificPrefix: not supported
  • honorificSuffix: not supported

Windows Quirks

  • formatted: It is identical to displayName

ContactOrganization

The ContactOrganization object stores a contact's organization properties. A Contact object stores one or more ContactOrganization objects in an array.

Properties

  • pref: Set to true if this ContactOrganization contains the user's preferred value. (boolean)
  • type: A string that indicates what type of field this is, home for example. _(DOMString)
  • name: The name of the organization. (DOMString)
  • department: The department the contract works for. (DOMString)
  • title: The contact's title at the organization. (DOMString)

Supported Platforms

  • Android
  • BlackBerry 10
  • Firefox OS
  • iOS
  • Windows Phone 8
  • Windows (Windows 8.1 and Windows Phone 8.1 devices only)

Example

function onSuccess(contacts) {
    for (var i = 0; i < contacts.length; i++) {
        for (var j = 0; j < contacts[i].organizations.length; j++) {
            alert("Pref: "      + contacts[i].organizations[j].pref       + "\n" +
                "Type: "        + contacts[i].organizations[j].type       + "\n" +
                "Name: "        + contacts[i].organizations[j].name       + "\n" +
                "Department: "  + contacts[i].organizations[j].department + "\n" +
                "Title: "       + contacts[i].organizations[j].title);
        }
    }
};

function onError(contactError) {
    alert('onError!');
};

var options = new ContactFindOptions();
options.filter = "";
filter = ["displayName", "organizations"];
navigator.contacts.find(filter, onSuccess, onError, options);

Android 2.X Quirks

  • pref: Not supported by Android 2.X devices, returning false.

BlackBerry 10 Quirks

  • pref: Not supported by BlackBerry devices, returning false.
  • type: Not supported by BlackBerry devices, returning null.
  • name: Partially supported. The first organization name is stored in the BlackBerry company field.
  • department: Not supported, returning null.
  • title: Partially supported. The first organization title is stored in the BlackBerry jobTitle field.

Firefox OS Quirks

  • pref: Not supported
  • type: Not supported
  • department: Not supported
  • Fields name and title stored in org and jobTitle.

iOS Quirks

  • pref: Not supported on iOS devices, returning false.
  • type: Not supported on iOS devices, returning null.
  • name: Partially supported. The first organization name is stored in the iOSkABPersonOrganizationProperty field.
  • department: Partially supported. The first department name is stored in the iOSkABPersonDepartmentProperty field.
  • title: Partially supported. The first title is stored in the iOS kABPersonJobTitleProperty field.

Windows Quirks

  • pref: Not supported, returning false.
  • type: Not supported, returning null.
.
Source: https://github.com/apache/cordova-plugin-contacts

How To Get Contact Numbers Via Cordova PhoneGap

.

ContactsPhoneNumbers Flattr this git repo

Cross-platform plugin for Cordova / PhoneGap to list all the contacts with at least a phone number.

Installing the plugin

   cordova plugin add https://github.com/dbaq/cordova-plugin-contacts-phone-numbers.git

Using the plugin

The plugin creates the object navigator.contactsPhoneNumbers with the methods
list(success, fail)
A full example could be:
   //
   //
   // after deviceready
   //
   //
   navigator.contactsPhoneNumbers.list(function(contacts) {
      console.log(contacts.length + ' contacts found');
      for(var i = 0; i < contacts.length; i++) {
         console.log(contacts[i].id + " - " + contacts[i].displayName);
         for(var j = 0; j < contacts[i].phoneNumbers.length; j++) {
            var phone = contacts[i].phoneNumbers[j];
            console.log("===> " + phone.type + "  " + phone.number + " (" + phone.normalizedNumber+ ")"); 
         }
      }
   }, function(error) {
      console.error(error);
   });

JSON Response format

The success callback function contains an array of contacts.
Each entry contains:
  • the unique contact id
  • the name of the contact (first name, last name, display name)
  • an array containing the number, the normalizedNumber and the type of the number (WORK,MOBILEHOME or OTHER)
Here is a sample of what you can get:
    [{
        "id": "1",
        "firstName": "Kate",
        "lastName": "Bell",
        "displayName": "Kate Bell",
        "phoneNumbers": [{
            "number": "(555) 564-8583",
            "normalizedNumber": "(555) 564-8583",
            "type": "MOBILE"
        }, {
            "number": "(415) 555-3695",
            "normalizedNumber": "(415) 555-3695",
            "type": "OTHER"
        }]
    }, {
        "id": "2",
        "firstName": "Daniel",
        "lastName": "Higgins",
        "displayName": "Daniel Higgins",
        "phoneNumbers": [{
            "number": "555-478-7672",
            "normalizedNumber": "555-478-7672",
            "type": "HOME"
        }, {
            "number": "(408) 555-5270",
            "normalizedNumber": "(408) 555-5270",
            "type": "MOBILE"
        }, {
            "number": "(408) 555-3514",
            "normalizedNumber": "(408) 555-3514",
            "type": "OTHER"
        }]
    }, {
        "id": "3",
        "firstName": "John",
        "lastName": "Appleseed",
        "displayName": "John Appleseed",
        "phoneNumbers": [{
            "number": "888-555-5512",
            "normalizedNumber": "888-555-5512",
            "type": "MOBILE"
        }, {
            "number": "888-555-1212",
            "normalizedNumber": "888-555-1212",
            "type": "HOME"
        }]
    }]

Behaviour

The plugin retrieves ONLY the contacts containing one or more phone numbers. It does not allow to modify them (use the official cordova contacts plugin for that).
With the official plugin, it is difficult and inefficient[1] to retrieve the list of all the contacts with at least a phone number (for Android at least). I needed a fastest way to retrieve a simple list containing just the name and the list of phone numbers.
If you need more fields like the email address or if you also need to retrieve the contacts without email address, we can add an option, open an issue and I'll see what I can do.
[1] When I say difficult and inefficient, it is because on Android, all your Gmail contacts are returned as a contact. See this issue on stackoverflow. With the official plugin you have to retrieve all the contacts and then iterate over the result to filter out what you want.
I executed a small benchmark on my Nexus 5 with Lollipop. The code calls both plugins and displays the result in the console. On this phone I have 1028 contacts but only 71 contacts have at least a phone number. Of course the performances depends on the number of contacts with phone numbers.
cordova-plugin-contacts
*  1 call: 
    try 1: 2.527s
    try 2: 2.581s
    try 3: 2.221s 

    => average of 2.443s

* 10 calls: 
    try 1: 6.048s 
    try 2: 9.196s 
    try 3: 8.981s

    => average of 8.075s for 10 calls
cordova-plugin-contacts-phone-numbers
*  1 call 
    try 1: 0.145s 
    try 2: 0.185s 
    try 3: 0.286s

    => average of 0.205s

* 10 calls: 
    try 1: 1.195s 
    try 2: 1.211s 
    try 3: 1.351s

    => average of 1.252s for 10 calls

iOS and Android

The plugin works with iOS and Android.
iOS does not provide a normalized number like Android. So number === normalizedNumber for iOS.
The Android code is heavily inspired from the official plugin with some tweaks to improve the perfomances.

Contributing

Thanks for considering contributing to this project.

Finding something to do

Ask, or pick an issue and comment on it announcing your desire to work on it. Ideally wait until we assign it to you to minimize work duplication.

Reporting an issue

  • Search existing issues before raising a new one.
  • Include as much detail as possible.

Pull requests

  • Make it clear in the issue tracker what you are working on, so that someone else doesn't duplicate the work.
  • Use a feature branch, not master.
  • Rebase your feature branch onto origin/master before raising the PR.
  • Keep up to date with changes in master so your PR is easy to merge.
  • Be descriptive in your PR message: what is it for, why is it needed, etc.
  • Make sure the tests pass
  • Squash related commits as much as possible.

Coding style

  • Try to match the existing indent style.
  • Don't mix platform-specific stuff into the main code.

Licence

The MIT License
Copyright (c) 2013 Didier Baquier
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.
Source: https://github.com/dbaq/cordova-plugin-contacts-phone-numbers
.
Example: http://pastebin.com/AvN1GUfn

Tuesday, October 6, 2015

How To Get Phone Number Via Cordova PhoneGap

.

TelephoneNumber plugin for Phonegap

The telephone number plugin allows you to retreive the devices phone numberfrom your PhoneGap application.

Adding the Plugin to your project

Using this plugin requires Android PhoneGap.
  1. To install the plugin, copy the www/telephonenumber.js file to your project's www folder and include a reference to it in your html file after cordova.js.
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8" src="telephonenumber.js"></script>
  2. Create a directory within your project called "src/com/simonmacdonald/cordova/plugins" and copy src/com/simonmacdonald/cordova/plugins/TelephoneNumber.java into it.
  3. In your res/xml/config.xml file add the following line:
    <plugin name="TelephoneNumber" value="com.simonmacdonald.cordova.plugins.TelephoneNumber"/>

Using the plugin

You create a new object that represents the plugin using cordova.require. Then you can call the 'get' method on that object providing a success callback which will be called with a result value that is the devices phone number.
  /**
    * get the devices phone number.
    */
  get(success, failure)
Sample use:
var telephoneNumber = cordova.require("cordova/plugin/telephonenumber");
telephoneNumber.get(function(result) {
        console.log("simSerialNumber = " + result.simSerialNumber); // number sim 
        console.log("line1Number = " + result.line1Number); // telephone number (if insert sim)
    }, function() {
        console.log("error");
    });

RELEASE NOTES

December 6, 2012

  • Initial release

BUGS AND CONTRIBUTIONS

LICENSE

This plugin is available under the MIT License (2008). The text of the MIT license is reproduced below.

The MIT License

Copyright (c) <2012>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.
Source: https://github.com/rotorgames/phonegap-telephonenumber-plugin
.
Patebin: http://pastebin.com/gHuiSZRN (index.html example)

How to get Phone SIM Card details using Cordova PhoneGap Plug Ins

.

cordova-plugin-carrier

What is it?

cordova-plugin-carrier is a cordova plugin to get the device's carrier name, mcc, mnc and country code. The information comes from the device's SIM card.

Installation

The plugin works on both Android and iOS platforms. To install it, go to your project dir and run this command:
cordova plugin add br.com.dtmtec.plugins.carrier

Usage

On both Android and iOS, the plugin returns to the app an JSON with the following properties: carrierName, countryCode, mcc, mnc.
<script>
  function alertCarrier() {
   var succ = function (data) {
     alert(data['carrierName']);
     alert(data['countryCode']);
     alert(data['mcc']);
     alert(data['mnc']);
   }

   var err = function () {
     alert('Error!');
   }

   window.plugins.carrier.getCarrierInfo(succ, err)
  }

  document.addEventListener('deviceready', alertCarrier, false);
</script>
.
Source: https://github.com/dtmtec/cordova-plugin-carrier
.
Patebin: http://pastebin.com/H5h1VBqb

How to use Google+ OAuth in Cordova PhoneGap

.

Google+ Cordova/PhoneGap Plugin

0. Index

  1. Description
  2. Screenshots
  3. Google+ API setup
  4. Installation (CLI / Plugman)
  5. Installation (PhoneGap Build)
  6. Usage
  7. Troubleshooting
  8. Changelog
  9. License

1. Description

This plugin allows you to log on with your Google account on iOS and Android. You will not only get the email address of the user, but also stuff like their full name and gender.

2. Screenshots

Android
    
iOS
     

3. Google+ API setup

To communicate with Google+ you need to do some tedious setup, sorry.

iOS

To get your iOS API key, follow Step 1 of this guide get a configuration file here. This GoogleService-Info.plist file contains the REVERSED_CLIENT_ID you'll need during installation.

Android

To configure Android, follow Step 1 of this guide
Make sure you execute the keytool steps as well or authentication will fail.

4. Installation (PhoneGap CLI / Cordova CLI)

This plugin is compatible with Cordova Plugman, compatible with PhoneGap 3.0 CLI, here's how it works with the CLI (backup your project first!):
Using the Cordova CLI and npm
$ cordova plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid
$ cordova prepare
To fetch the latest version from GitHub, use
$ cordova plugin add https://github.com/EddyVerbruggen/cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid
$ cordova prepare
GooglePlus.js is brought in automatically. There is no need to change or add anything in your html.

5. Installation (PhoneGap Build)

Add this to your config.xml:
<gap:plugin name="cordova-plugin-googleplus" source="npm">
  <param name="REVERSED_CLIENT_ID" value="myreversedclientid" />
</gap:plugin>

6. Usage

Check the demo app to get you going quickly, or hurt yourself and follow these steps.
Note that none of these methods should be called before deviceready has fired.

isAvailable

You'll want to check this before showing a 'Sign in with Google+' button.
On iOS it will check whether or not the Google+ app is installed. If it's not and you invoke the loginfunction, your app will redirect to Safari which seems an app rejection reason these days.
On Android it will check whether or not Google Play Services is available. It's more likely than not that it is.
window.plugins.googleplus.isAvailable(
    function (available) {
      if (available) {
        // show the Google+ sign-in button
      }
    }
);

Login

window.plugins.googleplus.login(
    {
      'scopes': '... ', // optional space-separated list of scopes, the default is sufficient for login and basic profile info
      'offline': true, // optional and required for Android only - if set to true the plugin will also return the OAuth access token, that can be used to sign in to some third party services that don't accept a Cross-client identity token (ex. Firebase)
      'webApiKey': 'api of web app', // optional API key of your Web application from Credentials settings of your project - if you set it the returned idToken will allow sign in to services like Azure Mobile Services
      // there is no API key for Android; you app is wired to the Google+ API by listing your package name in the google dev console and signing your apk (which you have done in chapter 4)
    },
    function (obj) {
      alert(JSON.stringify(obj)); // do something useful instead of alerting
    },
    function (msg) {
      alert('error: ' + msg);
    }
);
Note that if you're only targeting Android you can pass {} for the first argument.
The success callback (second argument) gets a JSON object with the following contents, with example data of my Google+ account:
 obj.email        // 'eddyverbruggen@gmail.com'
 obj.userId       // user id
 obj.displayName  // 'Eddy Verbruggen'
 obj.imageUrl     // 'http://link-to-my-profilepic.google.com'
 obj.idToken
 obj.oauthToken

 // these are only available on Android at the moment
 obj.gender       // 'male' (other options are 'female' and 'unknown'
 obj.givenName    // 'Eddy'
 obj.middleName   // null (or undefined, depending on the platform)
 obj.familyName   // 'Verbruggen'
 obj.birthday     // '1977-04-22'
 obj.ageRangeMin  // 21 (or null or undefined or a different number)
 obj.ageRangeMax  // null (or undefined or a number)

Try silent login

When the user comes back to your app and you're not sure if he needs to log in, you can calltrySilentLogin to try logging him in.
If it succeeds you will get the same object as the login function gets, but if it fails it will not show the authentication dialog to the user.
The code is exactly the same a login, except for the function name.
window.plugins.googleplus.trySilentLogin(
    {
      'offline': true, // optional and required for Android only - if set to true the plugin will also return the OAuth access token, that can be used to sign in to some third party services that don't accept a Cross-client identity token (ex. Firebase)
      'webApiKey': 'api of web app' // optional API key of your Web application from Credentials settings of your project - if you set it the returned idToken will allow sign in to services like Azure Mobile Services 
    },
    function (obj) {
      alert(JSON.stringify(obj)); // do something useful instead of alerting
    },
    function (msg) {
      alert('error: ' + msg);
    }
);

logout

This will clear the OAuth2 token.
window.plugins.googleplus.logout(
    function (msg) {
      alert(msg); // do something useful instead of alerting
    }
);

disconnect

This will clear the OAuth2 token and forget which account was used to login. On Android this will always force the user to authenticate the app again, on iOS using logout seems to do the job already. Need to investigate this a bit more..
window.plugins.googleplus.disconnect(
    function (msg) {
      alert(msg); // do something useful instead of alerting
    }
);

7. Troubleshooting

  • Q: After authentication I'm not redirected back to my app.
  • A: You probably changed the bundle id of your app after installing this plugin. Make sure that (on iOS) the CFBundleURLTypes bit in your .plist file is the same as the actual bundle id originating from config.xml.
  • Q: I can't get authentication to work on Android. And why is there no ANDROID API KEY?
  • A: On Android you need to execute the keytool steps, see the installation instructions for details.

8. Changelog

4.0.3: On iOS isAvailable always returns try since that should be fine with the new Google SignIn framework. Re-added imageUrl to the result of SignIn on iOS. 4.0.1: Login on Android would crash the app if isAvailable was invoked beforehand. 4.0.0: Removed the need for iosApiKey, reverted Android to Google playservices framework for wider compatibility, documented scopes feature a bit. 3.0.0: Using Google Sign-In for iOS, instead of Google+. 1.1.0: Added isAvailable, for issue #371.0.0: Initial version supporting iOS and Android

9. License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
.
Source: https://github.com/EddyVerbruggen/cordova-plugin-googleplus