Contacts

  • Revision slug: WebAPI/Contacts
  • Revision title: Contacts
  • Revision id: 439659
  • Created:
  • Creator: Jeremie
  • Is current revision? No
  • Comment

Revision Content

{{ non-standard_header() }}

{{ B2GOnlyHeader2('privileged') }}

Summary

The Contacts API provides a simple interface to manage user's contacts stored in the system's address book. A typical use case of the Contacts API is the implementation of an application to manage said address book.

Note: Because personal information regarding a user's contact are pieces of sensitive data, only privileged and certified apps are allow to directly access that API. Other applications are encouraged to use Web Activities to delegate operations on contacts.

Managing contacts

Contacts stored in the system's address book are accessible through the {{domxref("window.navigator.mozContacts","navigator.mozContacts")}} property, which is itself an instance of the {{domxref("ContactManager")}} interface.

Adding a contact

Creating a new entry in the system's address book is made in two steps:

  1. Instentiate a new {{domxref("mozContact")}} object and field all its necessary properties. The {{domxref("mozContact")}} interface defines all the possible properties for a given contact. Those properties are mostly the same as the ones define in the vCard 4.0 specification, with the following exceptions:
    • The vCard N attribute is split in 5 properties: {{domxref("mozContact.familyName","familyName")}}, {{domxref("mozContact.givenName","givenName")}}, {{domxref("mozContact.additionalName","additionalName")}}, {{domxref("mozContact.honorificPrefix","honorificPrefix")}}, {{domxref("mozContact.honorificSuffix","honorificSuffix")}}
    • The vCard FN attribute is renamed {{domxref("mozContact.name","name")}}
    • The vCard GENDER attribute is split in 2 properties: {{domxref("mozContact.sex","sex")}}, {{domxref("mozContact.genderIdentity","genderIdentity")}}
  2. Use the {{domxref("ContactManager.save()")}} method with the contact object as its first parameter. The method returns a {{domxref("DOMRequest")}} to keep track of the save operation's success or error.
var person = new mozContact();
person.givenName  = ["John"];
person.familyName = ["Doe"];
person.nickName   = ["No kidding"];

var saving = navigator.mozContacts.save(person);

saving.onsuccess = function() {
  console.log('new contact saved');
  // This update the person as it is stored
  // It includes it's internal unique ID
  person = saving.result;
};

saving.onerror = function(err) {
  console.error(err);
};

Finding a contact

There is two methods to retrieve contact from the system's address book:

  • {{domxref("ContactManager.find()")}} to retrieve a specific list of contacts;
  • {{domxref("ContactManager.getAll()")}} to retrieve all the contacts

Both methods expect a parameter which is an object that defines the filter and sort options. getAll only accepts the sort options. Those options are:

  • sortBy: A string representing the field by which the results of the search are sorted. Currently only givenName and familyName are supported.
  • sortOrder: A string indicating the result's sort order. Possible values are descending or ascending.

And the filter options:

  • filterBy: A array of strings representing all the fields to filter by.
  • filterValue: The value to match against.
  • filterOp: The filter comparison operator to use. Possible values are equals, startsWith,and match, the latter being specific to telephone numbers.
  • filterLimit: The number of contacts to retrieve for the {{domxref("ContactManager.find()","find")}} method.

Both methods return a {{domxref("DOMRequest")}} object to access the success or error of a search.

If the search is successful, the result of the search is available in the {{domxref("DOMRequest.result")}} property as either an Array of {{domxref("mozContact")}} objects for find(), or a {{domxref("DOMCursor")}} object for getAll(). To receive the next result in the list, call the cursor's continue() method.

var options = {
  filterValue : "John",
  filterBy    : ["givenName","name","nickName"],
  filterOp    : "contains",
  filterLimit : 1,
  sortBy      : "familyName"
  sortOrder   : "ascending"
}

var search = navigator.mozContacts.find(options);

search.onsuccess = function() {
  if (search.result.length === 1) {
    var person = search.result[0];
    console.log("Found:" + person.givenName[0] + " " + person.familyName[0]);
  } else {
    console.log("Sorry, there is no such contact.")
  }
}

search.onerror = function() {
  console.warn("Uh! Something goes wrong, no result found!");
}

var allContacts = navigator.mozContacts.getAll({sortBy: "familyName", sortOrder: "descending"});

allContacts.onsuccess = function(event) {
  var cursor = event.target;
  if (cursor.result) {
    console.log("Found: " + cursor.result.givenName[0] + " " + cursor.result.familyName[0]);
    cursor.continue();
  } else {
    console.log("No more contacts");
  }
}

allContacts.onerror = function() {
  console.warn("Something went terribly wrong! :(");
}

Updating a contact

When retrieving a contact through {{domxref("ContactManager.find()","find()")}} or {{domxref("ContactManager.getAll()","getAll()")}} (or after a success call to {{domxref("ContactManager.save()","save()")}} for new contact), this contact has some meta-data attached to it:

  • A unique ID available via {{domxref("Contact.id")}}
  • A Date object within {{domxref("Contact.lastUpdated")}} representing the last time the contact was updated.

Updating the contact is just about changing its properties values then saving it through a call to the {{domxref("ContactManager.save()","save()")}} method.

Note: Each time a contact is added, updated or deleted a {{event("contactchange")}} event is fired in order to keep track of any change on the system's address book. This event can be handled with the {{domxref("ContactManager.oncontactchange")}} property.

Deleting a contact

A call to {{domxref("ContactManager.remove()")}} method will simply delete the {{domxref("mozContact")}} object that was passed in.

In some edge cases, it's also possible to get rid of the whole contacts. To do this, use {{domxref("ContactManager.clear()")}}. Be careful when calling that method, there is no way back.

Specifications

Specification Status Comment
{{ SpecName('Contacts', '', 'Contacts Manager API') }} {{ Spec2('Contacts') }} First Working Draft (unstable)
vCard Format Specification RFC RFC6350

Browser compatibility

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
basic support {{CompatNo()}} {{CompatNo()}} {{CompatNo()}} {{CompatNo()}} {{CompatNo()}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
basic support {{CompatNo()}} {{CompatNo()}} 18.0 {{CompatNo()}} {{CompatNo()}} {{CompatNo()}}

Gecko Note

As the specification is unstable, the Gecko implementation is completely non-standard.

See also

  • {{domxref("window.navigator.mozContacts","navigator.mozContacts")}}
  • {{domxref("mozContact")}}
  • {{domxref("ContactManager")}}
  • {{domxref("MozContactChangeEvent")}}

Revision Source

<p>{{ non-standard_header() }}</p>
<p>{{ B2GOnlyHeader2('privileged') }}</p>
<h2 id="Summary">Summary</h2>
<p>The Contacts API provides a simple interface to manage user's contacts stored in the system's address book. A typical use case of the Contacts API is the implementation of an application to manage said address book.</p>
<div class="note">
  <p><strong>Note:</strong> Because personal information regarding a user's contact are pieces of sensitive data, only privileged and certified apps are allow to directly access that API. Other applications are encouraged to use <a href="/en-US/docs/WebAPI/Web_Activities" title="/en-US/docs/WebAPI/Web_Activities">Web Activities</a> to delegate operations on contacts.</p>
</div>
<h2 id="Managing_contacts">Managing contacts</h2>
<p>Contacts stored in the system's address book are accessible through the {{domxref("window.navigator.mozContacts","navigator.mozContacts")}} property, which is itself an instance of the {{domxref("ContactManager")}} interface.</p>
<h3 id="Adding_a_contact">Adding a contact</h3>
<p>Creating a new entry in the system's address book is made in two steps:</p>
<ol>
  <li>Instentiate a new {{domxref("mozContact")}} object and field all its necessary properties. The {{domxref("mozContact")}} interface defines all the possible properties for a given contact. Those properties are mostly the same as the ones define in the vCard 4.0 specification, with the following exceptions:
    <ul>
      <li>The vCard N attribute is split in 5 properties: {{domxref("mozContact.familyName","familyName")}}, {{domxref("mozContact.givenName","givenName")}}, {{domxref("mozContact.additionalName","additionalName")}}, {{domxref("mozContact.honorificPrefix","honorificPrefix")}}, {{domxref("mozContact.honorificSuffix","honorificSuffix")}}</li>
      <li>The vCard FN attribute is renamed {{domxref("mozContact.name","name")}}</li>
      <li>The vCard GENDER attribute is split in 2 properties: {{domxref("mozContact.sex","sex")}}, {{domxref("mozContact.genderIdentity","genderIdentity")}}</li>
    </ul>
  </li>
  <li>Use the {{domxref("ContactManager.save()")}} method with the contact object as its first parameter. The method returns a {{domxref("DOMRequest")}} to keep track of the save operation's success or error.</li>
</ol>
<pre class="brush: js">
var person = new mozContact();
person.givenName  = ["John"];
person.familyName = ["Doe"];
person.nickName   = ["No kidding"];

var saving = navigator.mozContacts.save(person);

saving.onsuccess = function() {
  console.log('new contact saved');
  // This update the person as it is stored
  // It includes it's internal unique ID
  person = saving.result;
};

saving.onerror = function(err) {
  console.error(err);
};
</pre>
<h3 id="Finding_a_contact">Finding a contact</h3>
<p>There is two methods to retrieve contact from the system's address book:</p>
<ul>
  <li>{{domxref("ContactManager.find()")}} to retrieve a specific list of contacts;</li>
  <li>{{domxref("ContactManager.getAll()")}} to retrieve all the contacts</li>
</ul>
<p>Both methods expect a parameter which is an object that defines the filter and sort options. getAll only accepts the sort options. Those options are:</p>
<ul>
  <li><code>sortBy</code>: A string representing the field by which the results of the search are sorted. Currently only givenName and familyName are supported.</li>
  <li><code>sortOrder</code>: A string indicating the result's sort order. Possible values are <code>descending</code> or <code>ascending</code>.</li>
</ul>
<p>And the filter options:</p>
<ul>
  <li><code>filterBy</code>: A array of strings representing all the fields to filter by.</li>
  <li><code>filterValue</code>: The value to match against.</li>
  <li><code>filterOp</code>: The filter comparison operator to use. Possible values are <code>equals</code>, <code>startsWith</code>,and <code>match</code>, the latter being specific to telephone numbers.</li>
  <li><code>filterLimit</code>: The number of contacts to retrieve for the {{domxref("ContactManager.find()","find")}} method.</li>
</ul>
<p>Both methods return a {{domxref("DOMRequest")}} object to access the success or error of a search.</p>
<p>If the search is successful, the result of the search is available in the {{domxref("DOMRequest.result")}} property as either an Array of {{domxref("mozContact")}} objects for find(), or a {{domxref("DOMCursor")}} object for getAll(). To receive the next result in the list, call the cursor's continue() method.</p>
<pre class="brush: js">
var options = {
  filterValue : "John",
  filterBy    : ["givenName","name","nickName"],
  filterOp    : "contains",
  filterLimit : 1,
  sortBy      : "familyName"
  sortOrder   : "ascending"
}

var search = navigator.mozContacts.find(options);

search.onsuccess = function() {
  if (search.result.length === 1) {
    var person = search.result[0];
    console.log("Found:" + person.givenName[0] + " " + person.familyName[0]);
  } else {
    console.log("Sorry, there is no such contact.")
  }
}

search.onerror = function() {
  console.warn("Uh! Something goes wrong, no result found!");
}

var allContacts = navigator.mozContacts.getAll({sortBy: "familyName", sortOrder: "descending"});

allContacts.onsuccess = function(event) {
  var cursor = event.target;
  if (cursor.result) {
    console.log("Found: " + cursor.result.givenName[0] + " " + cursor.result.familyName[0]);
    cursor.continue();
  } else {
    console.log("No more contacts");
  }
}

allContacts.onerror = function() {
  console.warn("Something went terribly wrong! :(");
}
</pre>
<h3 id="Updating_a_contact">Updating a contact</h3>
<p>When retrieving a contact through {{domxref("ContactManager.find()","find()")}} or {{domxref("ContactManager.getAll()","getAll()")}} (or after a success call to {{domxref("ContactManager.save()","save()")}} for new contact), this contact has some meta-data attached to it:</p>
<ul>
  <li>A unique ID available via {{domxref("Contact.id")}}</li>
  <li>A <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Date" title="/en-US/docs/JavaScript/Reference/Global_Objects/Date">Date</a> object within {{domxref("Contact.lastUpdated")}} representing the last time the contact was updated.</li>
</ul>
<p>Updating the contact is just about changing its properties values then saving it through a call to the {{domxref("ContactManager.save()","save()")}} method.</p>
<div class="note">
  <p><strong>Note:</strong> Each time a contact is added, updated or deleted a {{event("contactchange")}} event is fired in order to keep track of any change on the system's address book. This event can be handled with the {{domxref("ContactManager.oncontactchange")}} property.</p>
</div>
<h3 id="Deleting_a_contact">Deleting a contact</h3>
<p>A call to {{domxref("ContactManager.remove()")}} method will simply delete the {{domxref("mozContact")}} object that was passed in.</p>
<p>In some edge cases, it's also possible to get rid of the whole contacts. To do this, use {{domxref("ContactManager.clear()")}}. Be careful when calling that method, there is no way back.</p>
<h2 id="Specifications" name="Specifications">Specifications</h2>
<table class="standard-table">
  <thead>
    <tr>
      <th scope="col">Specification</th>
      <th scope="col">Status</th>
      <th scope="col">Comment</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{ SpecName('Contacts', '', 'Contacts Manager API') }}</td>
      <td>{{ Spec2('Contacts') }}</td>
      <td>First Working Draft (unstable)</td>
    </tr>
    <tr>
      <td><a href="http://tools.ietf.org/html/rfc6350" title="http://tools.ietf.org/html/rfc6350">vCard Format Specification</a></td>
      <td>RFC</td>
      <td><code>RFC6350</code></td>
    </tr>
  </tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>basic support</td>
        <td>{{CompatNo()}}</td>
        <td>{{CompatNo()}}</td>
        <td>{{CompatNo()}}</td>
        <td>{{CompatNo()}}</td>
        <td>{{CompatNo()}}</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>basic support</td>
        <td>{{CompatNo()}}</td>
        <td>{{CompatNo()}}</td>
        <td>18.0</td>
        <td>{{CompatNo()}}</td>
        <td>{{CompatNo()}}</td>
        <td>{{CompatNo()}}</td>
      </tr>
    </tbody>
  </table>
</div>
<h3 id="Gecko_Note">Gecko Note</h3>
<p>As the specification is unstable, the Gecko implementation is completely non-standard.</p>
<h2 id="See_also">See also</h2>
<ul>
  <li>{{domxref("window.navigator.mozContacts","navigator.mozContacts")}}</li>
  <li>{{domxref("mozContact")}}</li>
  <li>{{domxref("ContactManager")}}</li>
  <li>{{domxref("MozContactChangeEvent")}}</li>
</ul>
Revert to this revision