The Contacts API defines the high-level interfaces required to obtain read access to a user's unified address book.

This API includes the following key interfaces:

This document represents the early consensus of the group on the scope and features of the proposed Contacts API. Issues and editors note in the document highlight some of the points on which the group is still working and would particularly like to get feedback.

Introduction

Every operating system and a large number of web-based service providers have different ways of representing address book information. Most users are required to maintain a plurality of contact lists which leads to multiple copies of address book data. This in turn often leads to disjoint and inconsistent information being stored across a user's address book providers.

When sharing contact data with third parties users are, more often than not, required to hand over access to their whole address book. Users are implicitly required to trust third parties with all of their data when, in reality, the user may only wish, or need, to share a subset of their address book information so that an application can fulfill its purpose.

This specification defines the concept of a user's unified address book - where address book data may be sourced from a plurality of sources - both online and locally. It then defines the interfaces through which third party applications can access a user's unified address book, with explicit user permission and filtering. The focus of this data sharing is on making the user aware of the data that they will share and putting them at the centre of the data sharing process; free to select both the extent to which they share their address book information and the ability to restrict which pieces of information related to which contact gets shared.

A set of Security and Privacy Considerations are presented for the discretion of both implementers of the Contacts API and recipients of contact information (i.e. web pages). This specification provides a set of non-normative User Interaction Guidelines demonstrating an example user experience that is compliant with the Security and Privacy Considerations described herein.

This specification also provides informative examples illustrating how to add and update contact information, utilizing existing web platform APIs.

The following code illustrates how to obtain contact information from a user's address book:

        function success (contacts) {
            // do something with resulting contact objects
            for (var i in contacts) alert(contacts[i].name);
            // ...
        }

        function error (err) {
            // do something with resulting error
            alert(err.code);
            // ...
        }

        // Perform an address book search. Obtain the 'name' and 'emails' properties 
        // and initially filter the list to Contact records containing 'Bob':
        navigator.contacts.find(  ['name', 'emails'], success, error, { filter: 'Bob', multiple: true } );
      

This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.

Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [[!WEBIDL]], as this specification uses that specification and terminology.

A conforming implementation is required to implement all fields defined in this specification.

Terminology

The terms document base URL, browsing context, event handler attribute, event handler event type, task, task source and task queues are defined by the HTML5 specification [[!HTML5]].

The task source used by this specification is the device task source.

To dispatch a success event means that an event with the name success, which does not bubble and is not cancellable, and which uses the Event interface, is to be dispatched at the ContactFindCB object.

To dispatch an error event means that an event with the name error, which does not bubble and is not cancellable, and which uses the Event interface, is to be dispatched at the ContactErrorCB object.

Security and Privacy Considerations

The API defined in this specification can be used to find contact information from a user's address books. This discloses information related to a user's contacts such as their phone numbers, email addresses and other personally identifying information. The distribution of this information could potentially compromise the user's privacy, or the user's contacts' privacy. A conforming implementation of this specification should provide a mechanism that protects the user's privacy and this mechanism should ensure that no contact information is retrievable without the user's express permission.

Privacy considerations for implementers of the Contacts API

A user agent should not provide contact information to Web sites without the express permission of the user. A user agent should acquire permission from the user, unless they have prearranged trust relationships with users, as described below. The user interface should include the document base URL. Those permissions that are acquired through the user interface and that are preserved beyond the current browsing session (i.e. beyond the time when the browsing context is navigated to another URL) should be revocable and a user agent should respect permission revocation.

Obtaining the user's express permission to access one API method does not imply the user has granted permission for the same Web site to access other methods provided by this API, or to access the same method with a different set of arguments, as part of the same permission context. If a user has expressed permission for an implementation to, e.g. find a set of existing contacts, the implementation should seek the user's express permission if and when any additional find function is called on this API.

A user agent may have prearranged trust relationships that do not require such user interfaces. For example, while a Web browser will present a user interface when a Web site performs an address book request, a Widget [[WIDGETS]] runtime may have a prearranged, delegated security relationship with the user and, as such, a suitable alternative security and privacy mechanism with which to authorize the retrieval of contact information.

Privacy considerations for recipients of contact information

Web sites operators that retrieve contacts information using this API are denoted as recipients below.

Recipients should only request contact information when necessary, and only use the contact information for the task for which it was provided to them.

Recipients should dispose of contact information once that task is completed, unless expressly permitted to retain it by the user. Recipients should also take measures to protect this information against unauthorized access. If contact information is stored, users should be allowed to update and delete this information.

The recipient of contact information should not retransmit the contact information without the user's express permission. Care should be taken when retransmitting and use of encryption is encouraged.

Recipients should clearly and conspicuously disclose the fact that they are collecting contact data, the purpose for the collection, how long the data is retained, how the data is secured, how the data is shared if it is shared, how users can access, update and delete the data, and any other choices that users have with respect to the data. This disclosure should include an explanation of any exceptions to the guidelines listed above.

Note that even if a user gives permission to share their contact information this can have serious privacy implications for those parties whose contacts are shared, as they may not wish such sharing to occur. This should be considered by web services when requesting and using such information.

Additional implementation considerations

Further to the requirements listed in the previous section, implementers of the Contacts API are also advised to consider the following aspects that can negatively affect the privacy of their users: in certain cases, users can inadvertently grant permission to the user agent to disclose their contacts to Web sites. In other cases, the content hosted at a certain URL changes in such a way that the previously granted contact permissions no longer apply as far as the user is concerned. Or the users might simply change their minds.

Predicting or preventing these situations is inherently difficult. Mitigation and in-depth defensive measures are an implementation responsibility and not prescribed by this specification. However, in designing these measures, implementers are advised to enable user awareness of contact sharing, and to provide easy access to interfaces that enable revocation of permissions that web applications have to access this API.

API Description

ServiceContacts interface

The ServiceContacts interface is exposed on the Navigator object [[NAVIGATOR]]. Its goal is to provide an access point to the functionality in this specification.

readonly attribute Contacts contacts
The object through which the contacts functionality can be accessed.

Contacts interface

The Contacts interface exposes a database of contact information that may be retrieved.

Multiple contact groups can be represented within this unified address book by specifying consistent categories values as part of individual Contact objects. Multiple contact groups can be displayed by filtering on the required categories values via the Contacts find() operation.

void find ()

Find contacts in the address book according to the find contacts process detailed below.

This method takes two, three or four arguments. When called, it starts the following find contacts process:

  1. Let successCallback be the callback indicated by the method's second argument.
  2. Let errorCallback be the callback indicated by the method's third argument, if any, or null otherwise.
  3. If successCallback is null, then throw a TypeError (as defined in [[WEBIDL]]).
  4. If there is a task from the device task source in one of the task queues (e.g. an existing find() operation is still pending a response), run these substeps:
    1. If errorCallback is not null, let error be a ContactError object whose code attribute has the value PENDING_OPERATION_ERROR and queue a task to invoke errorCallback with error as its argument.
    2. Abort this operation.
  5. Return, and run the remaining steps asynchronously.
  6. Let results be the array of Contact objects obtained by searching contacts in the address book according to the rules defined in Contact Search Processing, or null if the search has failed.
  7. If results is null, run these substeps:
    1. If errorCallback is not null, let error be a ContactError object whose code attribute has its value set according to the type of failure that occurred and queue a task to invoke errorCallback with error as its argument.
    2. Abort this operation.
  8. Queue a task to invoke successCallback with results as its argument.
DOMString[] fields
The search qualifier.
ContactFindCB successCB
Function to call when the asynchronous operation completes successfully.
optional ContactErrorCB errorCB
Function to call when the asynchronous operation fails.
optional ContactFindOptions options
The options to apply to the output of this method.

Contact interface

The Contact interface captures the properties of a contact object. All properties included in this interface have a corresponding definition in [[POCO-SCHEMA]], [[RFC2426]] (aka vCard), and [[OMA-CAB]], thereby allowing the API to be supported across implementations supporting these various contact formats.

All Contact objects MUST include all attributes supported by the implementation, regardless of whether these attributes have been assigned a null value or not. If a supported attribute has not been assigned a value by the user or the implementation, then this attribute MUST still be present in the resulting Contact object and MUST have a value of null.

Additional attributes MAY be included according to the provisions detailed in Extended Contact Properties and Parameters. If an extended attribute is supported by the current implementation and has not been assigned a value by the user or the implementation, then this extended attribute MUST still be present in the resulting Contact object and MUST have a value of null.

readonly attribute DOMString id

A globally unique identifier for the given Contact object.

An implementation MUST maintain this globally unique identifier when a Contact is added to an address book.

attribute DOMString? displayName

This attribute contains the name of this Contact in a form that is suitable for display to the user.

attribute ContactName? name

This attribute represents the full name of this Contact indicated by the name components associated with the ContactName object.

attribute DOMString? nickname

This attribute contains the nickname (or a casual name) for this Contact.

attribute ContactField[]? phoneNumbers

This attribute captures one or more phone numbers associated with this Contact.

attribute ContactField[]? emails

This attribute represents one or more email addresses associated with this Contact.

attribute ContactAddress[]? addresses

This attribute represents one or more physical addresses associated with this Contact.

attribute ContactField[]? ims

This attribute represents one or more instant messaging identifiers associated with this Contact.

attribute ContactOrganization[]? organizations

This attribute represents one or more organizations associated with this Contact.

attribute Date? birthday

This attribute contains birthday of this Contact.

The year value MAY be set to 0000 when the age of the Contact is private or the year is not available.

attribute DOMString? note

This attribute contains the personal notes (free-text) for this Contact that is managed by the user of the address book.

attribute ContactField[]? photos

This attribute represents one or more photos associated with this Contact.

The photos MUST be specified in the value attribute of the ContactField object by using a URL pointing to an image resource. The data: URI scheme may be used in order to provide inline data.

This attribute SHOULD NOT be used to send down arbitrary photos taken by this user, but specifically profile photos of the contact suitable for display when describing the contact.

attribute DOMString[]? categories

This attribute contains one or more user-defined categories/tags/labels associated with this Contact. e.g. "family", "favorite", "cryptozoologists".

attribute ContactField[]? urls

This attribute represents one or more URLs associated with this Contact e.g. personal web page, blog.

The web resources MUST be specified using the value attribute of the ContactField object, and its type field may be set to "blog" or "profile".

ContactName interface

The ContactName interface describes a contact's name.

attribute DOMString? familyName

This attribute contains the family name (also referred to as the last name) of this Contact.

attribute DOMString? givenName

This attribute contains the given name (also referred to as the first name) of this Contact.

attribute DOMString? middleName

This attribute contains the middle name of this Contact.

attribute DOMString? honorificPrefix

This attribute contains the honorific prefix (or title) of this Contact. E.g. Mr., Dr., Ms., Mrs.

attribute DOMString? honorificSuffix

This attribute contains the honorific suffix of this Contact. E.g. Jr., III, Sr.

ContactField interface

The ContactField interface is a reusable component that is used to capture contact fields of the Contact interface that have some modicum of structure.

attribute DOMString type

This attribute contains the type information for this ContactField and its content varies subject to the contact property this ContactField is representing. For example, if the ContactField is representing a phoneNumber property, the type attribute can be set to home, mobile; if the ContactField is representing the ims property, the type attribute could be set to xmpp, irc, bbm, etc.

attribute DOMString? value

This attribute contains the value for this ContactField and its content varies subject to the contact property this ContactField is representing. For example, if the ContactField is representing an email, the value attribute could be set to JoeSmith@example.com, and if the ContactField is representing a url, the value attribute can be set to http://www.example.org/joesmith, etc.

attribute boolean pref

This attribute indicates whether this instance of the ContactField is the preferred, or primary, value for the contact property this ContactField is representing in the Contact interface. By default, the value is false.

ContactAddress interface

The ContactAddress interface is a reusable component that is used to capture addresses within the Contact interface.

attribute boolean pref

This attribute indicates whether this instance of the ContactAddress is the preferred, or primary, value for the contact. By default, the value is false.

attribute DOMString? type

This attribute contains the type of address this object is representing (e.g. work, home, premises, etc).

attribute DOMString? streetAddress

This attribute contains the street address corresponding to this ContactAddress.

attribute DOMString? locality

This attribute contains the locality (or city) name corresponding to this ContactAddress.

attribute DOMString? region

This attribute contains the region (or state/province) name corresponding to this ContactAddress.

attribute DOMString? postalCode

This attribute contains the postal code (or zip) corresponding to this ContactAddress.

attribute DOMString? country

This attribute contains the country name corresponding to this ContactAddress.

ContactOrganization interface

The ContactOrganization interface is a reusable component that is used to support contact organisations within the Contact interface.

attribute boolean pref

This attribute indicates whether this instance of the ContactOrganization is the preferred, or primary, value for the contact. By default, the value is false.

attribute DOMString? type

This attribute contains the type of organization this object is representing.

attribute DOMString? name

The name of the organisation.

attribute DOMString? department

The department within which this Contact works.

attribute DOMString? title

The job title that the Contact holds inside this organisation.

ContactFindOptions interface

The ContactFindOptions interface describes the options that can be applied to contact searching. When a ContactFindOptions parameter is provided to the Contacts find() operation, it should be processed according to the provisions detailed in Options Processing.

attribute DOMString? filter
A string-based search filter which provides a hint to the user agent to facilitate contacts selection by the user.
attribute boolean? multiple
A boolean value to indicate whether multiple Contact objects are wanted as part of the Contacts find() operation. By default this option is set to false.

ContactFindCB interface

This is the wrapper interface for callbacks indicating success of the find() operation.

void onsuccess ()
Contact[] contactObjs
An array of Contact objects resulting from the given Contacts find() operation.

Event Handler Attributes

The following is the event handler attribute (and its corresponding event handler event type) that MUST be supported as a DOM attribute by the ContactFindCB object.

event handler attribute event handler event type
onsuccess success

ContactErrorCB interface

This is the wrapper interface for callbacks indicating failure of the find() operation.

void onerror ()
ContactError error
The ContactError object capturing the type of the error.

Event Handler Attributes

The following is the event handler attribute (and its corresponding event handler event type) that MUST be supported as a DOM attribute by the ContactErrorCB object.

event handler attribute event handler event type
onerror error

ContactError interface

The ContactError interface encapsulates all errors in the manipulation of Contact objects.

const unsigned short UNKNOWN_ERROR = 0
An unknown error occurred.
const unsigned short INVALID_ARGUMENT_ERROR = 1
An invalid parameter was provided when the requested method was invoked.
const unsigned short TIMEOUT_ERROR = 2
The requested method timed out before it could be completed.
const unsigned short PENDING_OPERATION_ERROR = 3
There is already a task in the device task source.
const unsigned short IO_ERROR = 4
An error occurred in communication with the underlying implementation that meant the requested method could not complete.
const unsigned short NOT_SUPPORTED_ERROR = 5
The requested method is not supported by the current implementation.
const unsigned short PERMISSION_DENIED_ERROR = 20
Access to the requested information was denied by the implementation or by the user.
readonly attribute unsigned short code
An error code assigned by an implementation when an error has occurred in Contacts API processing.

Contact Search Processing

The Contacts find() method provides an operation to search for one of more Contact objects within the Contacts database.

Search Qualifiers

The search qualifier provides an application with a way to request the specific subset of Contact properties it wishes to obtain in any resulting successful callback. The search qualifier is deployed to minimize the data that needs to be shared with an application in order to let that application fulfill its function on behalf of the user. The search qualifier is included within a Contacts find() operation as the fields parameter.

A search qualifier MUST be specified from a requesting application as a part of any Contacts find() operation.

If the search qualifier provided is of zero-length then the current Contacts find() operation and the current find() operation was invoked with a non-null errorCB parameter, then the user agent MUST invoke the errorCB function with an error code of INVALID_ARGUMENT_ERROR.

In the case that the search qualifier provided is of non-zero-length then the current Contacts find() operation MUST return only the matching Contact properties within any resulting Contact object(s).

If a provided search qualifier element (fields[x]) does not match a Contact attribute, fields[x] SHOULD be ignored when executing the current Contacts find() operation.

Advanced Search Qualifiers

We call composed attributes Contact attributes of types object, which contain information only available only through child attributes of that object, or array.

A requesting application MUST be able to request both the full composed Contact attribute and also be able to request individual parts of a composed Contact attribute in the search qualifier provided to a Contacts find() operation.

For example, the name attribute of a Contact object is defined to be of composed type ContactName. Therefore, a requesting application may request either the full composed attribute (i.e. name) or specific individual attributes of this composed attribute (i.e. name.familyName, name.givenName, name.middleName, name.honorificPrefix, name.honorificSuffix) as part of a Contacts find() operation's search qualifier.

In the case that a composed Contact attribute is defined as an array of composed objects, specific individual attributes can be referenced by using the composed attribute name, a dot (.) character and the individual attribute to be retrieved.

For example, the addresses attribute of Contact allows multiple ContactAddress objects to be defined. To request individual attributes of this composed attribute an application would request e.g. addresses.locality, addresses.region, etc.

The following Contact search is initiated:

 
     navigator.contacts( ['emails.value', 'name', 'friends'],
                         function(contacts) { 
                           for(i in contacts) {
                             for(j in contacts[i].emails)
                               alert(contacts[i].emails[j]);
                           }
                         } );
  

The above example logically implies:

  1. Return only the valid Contact attributes requested in the provided search qualifier (name, emails.value - friends is not a valid Contact attribute so ignore this element).

Options Processing

Search Cardinality

By default, the Contacts find() operation MUST return either an empty sequence or a single Contact object, accessible as part of the sequence returned in the ContactFindCB callback function.

If a ContactFindOptions object is provided to the Contacts find() operation and its multiple attribute is set to true, the Contacts find() operation MUST return either an empty sequence, a single Contact object or [X] number of Contact objects, accessible as part of the sequence returned in the ContactFindCB callback function.

Search Filters

A search filter may be specified from a requesting web application to provide a hint to the user agents as to which contacts the user can select to share with the application.

The search filter is defined through the filter attribute of the ContactFindOptions object provided to a Contacts find() operation.

The actual usage of this search filter is user-agent dependant, but is expected to represent the logical union of provided values that are matched therein.

Extended Contact Properties and Parameters

The properties and parameters defined on the Contact interface MAY be extended by implementers of this specification.

Non-standard, private properties and parameters MUST have a prefixed name starting with X (U+0058 LATIN CAPITAL LETTER X) or use a vendor-specific prefix. Extended properties and parameters can be defined bilaterally between user agents without outside registration or standardization.

It is RECOMMENDED that authors define both a formal vCard grammar and a WebIDL grammar for their proposed extension to ensure interoperability between vCard databases and other non-standard Contact databases and formats. It is also RECOMMENDED that authors provide documentation of their extension properties and parameters within the public domain.

A new parameter is required by Company X to provide information related to a user's accounts registered across different networks and services.

The [[WEBIDL]] syntax for this parameter is defined as follows:

 
attribute ContactAccount[] Xaccounts
One or more user accounts. See [[[POCO-SCHEMA]] Section 7.2.2. accounts].
attribute DOMString domain

See [[[POCO-SCHEMA]] Section 7.6. domain].

attribute DOMString username

See [[[POCO-SCHEMA]] Section 7.6. username].

attribute DOMString userid

See [[[POCO-SCHEMA]] Section 7.6. userid].

The corresponding vCard [[RFC2426]] notation for this parameter is defined as follows:

     The following ABNF grammar extends the grammar found in [[RFC2426]] (Section 4).
   
     X-ACCOUNT
   
     Purpose:  To specify the components of the accounts for the vCard 
        object.

     Value type:  A single structured text value, separated by the SEMI-
        COLON character (ASCII decimal 59).

     Cardinality:  (0,n)

     Special notes:  The structured type value consists of a sequence of
        account components.  The component values must be specified in
        their corresponding position.  The structured type value
        corresponds, in sequence, to the domain; the username; the userid.
        When a component value is missing, the associated component 
        separator must still be specified.    

        The text components are separated by the SEMI-COLON character
        (ASCII decimal 59).
      
     ABNF:
   
       X-ACCOUNT-param = ; no parameter allowed
       X-ACCOUNT-value = list-component 3(";" list-component)
  

This parameter will be used within the Contacts API as follows:

     var contact = ...; // ...obtain individual contact object
     for(var i in contact.Xaccounts) {
        alert(contact.Xaccounts[i].domain);   // thesocialnetwork.com
        alert(contact.Xaccounts[i].username); // null
        alert(contact.Xaccounts[i].userid);   // 344aesq2
     }            
  

This parameter will be used within the vCard format [[RFC2426]]] as follows:

     X-ACCOUNT;thesocialnetwork.com;;344aesq2
  

API Invocation via DOM Events

The API contained in this document can be invoked either programmatically (for example, inline within a general script) or resulting from the interaction of a user.

The interaction of a user is when a user invokes the API from an HTMLElement [[HTML5]] within the current browsing context via a valid auto-invocation event.

A valid auto-invocation event includes any of the following event types, as defined in [[!DOM-LEVEL-3-EVENTS]]:

The find() method on Contacts should, if the method was invoked by an interaction of a user (as opposed to having been created and executed in general script), display the Contact Picker directly.

User Interaction Guidelines

This specification is primarily intended to provide the user with the ability to view and control the contact information that may be shared from their unified address book. This annex provides some examples of a conformant user experience that this specification enables.

Accessing Contact Information - Example #1

A website requests access to a user's address book with the following code:

   <script type="text/javascript">
 
  function successContactFindCallback(contacts) {
      // do something with resulting contact objects
      for (var i in contacts) alert(contacts[i].name);
      // ...
  }

  function generalErrorCB(error) {
      // do something with resulting errors
      alert(error.code);
      // ...
  }

  // Perform an address book search. Obtain the 'name' and 'emails' properties 
  // and initially filter the list to Contact records containing 'Bob':
  navigator.contacts.find(['name', 'emails'],
                                  successContactFindCallback, 
                                  generalErrorCB,
                                  { filter: 'Bob', multiple: true }
                                 );
                               
  </script>
  

As a result of executing this code, the user agent may provide a non-blocking contact search notification as follows:

Contact Search Notification
(View as PNG)

If an additional find() operation is called by the current web application before the user has clicked 'Select' or 'Cancel' on the current notification, an error will be invoked with a code of PENDING_OPERATION_ERROR if that operation was defined with a non-null errorCB parameter.

If the user clicks 'Cancel', the errorCB, if non-null for the current find() operation, will be invoked with an error code of PERMISSION_DENIED_ERROR.

If the user clicks 'Select', the user agent may provide a contact picker, utilizing all of the parameters provided in the find() operation as follows:

Contact Picker
(View as PNG)

In this dialog, the user is provided with a summary of the sharing that the application is requesting and the option to select one or more contacts (as appropriate) from the user interface.

If an additional find() operation is called by the current web application before the user has clicked 'Select' or 'Cancel' on the current notification, an error will be invoked with a code of PENDING_OPERATION_ERROR if that operation was defined with a non-null errorCB parameter.

If the user clicks 'Cancel', the errorCB, if non-null for the current find() operation, will be invoked with an error code of PERMISSION_DENIED_ERROR.

If the user clicks 'Select', the ContactFindCB associated to the current find() operation will be invoked with the contact information selected by the user provided as the only parameter.

Further to this initial sharing of Contact information, the Security and Privacy Considerations section expects that the user should easily be able to review and revoke access that web applications have to this API at a later time.

Accessing Contact Information - Example #2

A website requests access to a user's address book with the following code:

  <input type="button" value="Share Contacts" onclick="getContacts()" />
 
  <script type="text/javascript">
    function successContactFindCallback(contacts) {
      // do something with resulting contact objects
      for (var i in contacts) alert(contacts[i].name);
      // ...
    }

    function generalErrorCB(error) {
      // do something with resulting errors
      alert(error.code);
      // ...
    }
  
    function getContacts() {
      // Perform an address book search. Obtain the 'name' and 'emails' properties 
      // and initially filter the list to Contact records containing 'Bob':
      navigator.contacts.find( ['name', 'emails'],
                              successContactFindCallback, 
                              generalErrorCB,
                              { filter: 'Bob', multiple: true } );
    }
  </script>
  

This code may render as follows within the user agent:

Contact Search via DOM Events
(View as PNG)

If the user clicks on the rendered button element then the user agent may directly provide a contact picker, as defined in API Invocation via DOM Events, utilizing all of the parameters provided in the find() operation as follows:

Contact Picker
(View as PNG)

In this dialog, the user is provided with a summary of the sharing that the application is requesting and the option to select one or more contacts (as appropriate) from the user interface.

If an additional find() operation is called by the current web application before the user has clicked 'Select' or 'Cancel' on the current notification, an error will be invoked with a code of PENDING_OPERATION_ERROR if that operation was defined with a non-null errorCB parameter.

If the user clicks 'Cancel', the errorCB, if non-null for the current find() operation, will be invoked with an error code of PERMISSION_DENIED_ERROR.

If the user clicks 'Select', the ContactFindCB associated to the current find() operation will be invoked with the contact information selected by the user provided as the only parameter.

Further to this initial sharing of Contact information, the Security and Privacy Considerations section expects that the user should easily be able to review and revoke access that web applications have to this API at a later time.

Adding and Updating Contacts

The ability to add and update contact information is not a function of the API provided in this specification. Instead, the intention is to reuse existing web platform APIs and paradigms in order to achieve add and update functionality.

In this section we show how the existing web platform would be used to provide add and update writeback functionality to allow users to add new contacts or update existing contacts from a web page to their unified address book.

A valid Contact resource is a web resource with a .vcard or .vcf filename extension or a web resource with a MIME-type matching a valid media type. A vCard object is a text-based representation of contact information provided according to any version of the vCard family of specifications.

Need to add informative references to all specs within the 'vCard family of specifications'.

To handle the saving of a new Contact, a user agent should register as the default handler for any valid Contact resource.

A valid media type will be one of the following web resource MIME types:

On invocation of a valid Contact resource, the user agent should, on successful download of the valid Contact resource, store the given resource in the user's unified address book according to the rule for storing a Contact resource. As part of this standard download process, the user agent may present a dialog to the user allowing them to select a different application with which to handle the given resource, thereby overriding the use of the unified address book for the storage of the data contained therein and bypassing the rule for storing a Contact resource.

The rule for storing a Contact resource is defined as follows:

Let Contact be the parsed key/value pairs contained in the valid Contact resource.

  1. If Contact contains a UID key then process the valid Contact resource as follows.
    1. Let MatchedContact be the result of obtaining a Contact object from the user's unified address book that matches exactly the value of the UID provided.
    2. If a MatchedContact has been found (i.e. MatchedContact is not-null) then update the contents of MatchedContact with the contents of Contact and exit this rule.
  2. Save the contents of Contact in the user's unified address book as a new Contact object.

As part of the rule for storing a Contact resource, the user agent may provide additional dialogs to the user after successful completion of the download and before the Contact information is saved to the unified address book, such as to show a preview of the Contact information contained therein as it will be stored in the user's unified address book. The user may be able to override the information provided before accepting the additions and permanently storing the given data in their unified address book.

Adding a new Contact

A web page can dynamically generate a vCard object on the client side for download to the user's unified address book via either data: URIs [[RFC2397]] or using the [[FILE-WRITER]] and [[FILE-API]] interfaces. The following examples show two methods for creating a vCard object dynamically and then presenting this to the user. The user may then save this information by clicking on the presented information, download the dynamically generated vCard object and invoke a suitable application with which to handle the dynamic resource.

  <a id="vcard">Save our Contact Details</a>

  <script type="text/javascript">
    var vcard = 'BEGIN:VCARD\r\n' +
                'VERSION:2.1\r\n' +
                'N:Doe;John\r\n' +
                'FN:John Doe\r\n' +
                'TEL;WORK;VOICE:123456\r\n' +
                'END:VCARD';

    // assign vCard as a Data URI to an anchor element for presentation and download by the user
    document.getElementById('vcard').href = "data:text/x-vcard;charset=utf-8," + encodeURIComponent( vcard ); 
  </script>
  
  <a id="vcard">Save our Contact Details</a>

  <script type="text/javascript">
    // obtain an ArrayBuffer consisting of valid vCard syntax (out of scope)
    var vCardObj = getVCard( /* ... */ );
            
    // create a new vCard Blob [[FILE-WRITER]]
    var contactBlobBuilder = new BlobBuilder();
    contactBlobBuilder.append( vCardObj );
    var contactBlob = contactBlobBuilder.getBlob( "text/x-vcard" );

    // obtain a vCard Blob URL [[FILE-API]]
    var contactBlobURL = window.URL.createObjectUrl( contactBlob );

    // assign vCard Blob URL to an anchor element for presentation and download by the user
    document.getElementById('vcard').href = contactBlobURL; 
  </script>
  

Updating an existing Contact

To update an existing Contact, the user must have already shared the contact information to edit with the current web page via the find() operation of the Contacts interface. This section assumes that the user is already sharing some contact information with the current web page via this process.

If this existing Contact information is to be updated in the user's unified address book then the developer will assign the id attribute, as returned in the Contact object, as the UID property of any resulting vCard object to be processed by the user agent according to the rule for storing a Contact resource.

The examples below show two methods for updating an existing Contact in the user's unified address book by maintaining a valid UID property while changing other parameters of the Contact card. The user is then required to click on the resulting anchor element to download the modified Contact resource.

  <a id="vcard">Save our Contact Details</a>

  <script type="text/javascript">
    // Obtain a single existing Contact object resulting from navigator.contacts.find()
    var existingContactObj = ...;
  
    var vcard = 'BEGIN:VCARD\r\n' +
                'VERSION:3.0\r\n' +
                'UID:' + existingContactObj.id + '\r\n' + // assign the Contact.id to a UID property   
                'N:Doe;John\r\n' +
                'FN:John Doe\r\n' +
                'TEL;HOME;VOICE:654321\r\n' +
                'END:VCARD';

    // assign vCard as a Data URI to an anchor element for presentation and download by the user
    document.getElementById('vcard').href = "data:text/x-vcard;charset=utf-8," + encodeURIComponent( vcard ); 
  </script>
  
  <a id="vcard">Update our Contact Details</a>

  <script type="text/javascript">
    // Obtain a single existing Contact object resulting from navigator.contacts.find()
    var existingContactObj = ...;
  
    // Modify some parameters as required. e.g. add a new phone number
    existingContactObj.phoneNumbers.push({
      type: 'home', 
      value: '654321'
    });

    // With the existing Contact object, create an ArrayBuffer consisting of valid vCard 
    // syntax (out of scope) making sure to set the resulting vCard UID property to 
    // the id parameter returned in the existing Contact object
    var vCardObj = getVCard( existingContactObj );

    // create a new vCard Blob [[FILE-WRITER]]
    var contactBlobBuilder = new BlobBuilder();
    contactBlobBuilder.append( vCardObj );
    var contactBlob = contactBlobBuilder.getBlob( "text/x-vcard" );

    // obtain a vCard Blob URL [[FILE-API]]
    var contactBlobURL = window.URL.createObjectUrl( contactBlob );

    // assign vCard Blob URL to an anchor element for presentation and download by the user
    document.getElementById('vcard').href = contactBlobURL; 
  </script>