You are on page 1of 13
‘110112023 18:08, ‘Contacts - Apache Cordova Tobie of Contents + mee ‘This version of the documentation is outdated! Click here forthe latest released version, /does/en/latest/) ‘master. (https //github.com/apache /cordova-plugin-contacts releases) ‘Android 4.4 Android 5.2 Android 6.0 ose: PBuild Status thtp/cordova- Build Status tntp/eordova- Build Status (tp//eordova- Build Status thet Cleloudaapnet 8080/job/cordova-cicloudappnet 8080/job/cordova- _cicloucapp not Bo80/job/cordova- _cicloudapp not 8080 periodic- peroctc- periodic~ periodic-bulld/PLE bulld/PLATFORM.android- buile/PLATFORM-android- bulld/PLATFORM-android ‘93PLUGIN-cord 44PLUGIN-cordova-plugin- 54 PLUGINscordova-plugin- 6.0 PLUGIN:cordova-plugi contacts ccontacts/) conlacts/) ccontacts/) cordova-plugin-contacts ‘This plugin defines a global navigator.contacts object which provides access lo the device contacts database ‘Although the object is attached to the global scoped navigator. itis not avaliable unt after the deviceready event. cocanent.addventListener(“devicerendy", enbeviceteacy, false): function onbeviceteady() { corso. Log(navigator. contacts): } WARNING: Collsction and use of contact data raises important privacy issues. Your app's privacy policy should discuss how the apo uses contact data anc whether it's shared wth any other parties. Contact information Is considored sonsitive because it reveals the people with whem a person communicates. Therefore, in adeiton to the ape’s privacy policy. you shoul strongly consider providing a just-in-time notice before the app accesses or uses contact data, ithe device operating systom doesnt do so already, That notice snouls provide the same information noted above, as wel as obtaining the user's permission (eg. by presenting choices for OK and No Thanks), Note that some app rrarketplaces may require the app to provide ajust-in-time notice and obtain the user's permission before accessing contact data. clear and easy-to-undorstand sor experionce surrounding the use of contact data holps avoid user confusion and percolved misuse of contact data. For ‘more information, please see the Privacy Guide Untp//cordove apache.org/docs/en/latest/quide /appdev privacy index him Report issues with this plugin on the Apache Cordova issue tracker intips//issuesapachenrg/jira/issues/? Jol projecti20%30%20CBX20AND%2ostatus%20ink20%e8Open'k2C%20% 7aln%20Progress?.22%2C%20Reopened2X20ANDK2oresolut Installation & This requires cordova 50° (current stable v1.00) jugin add cordovaplugin-contacts Older versions of cardova can still install vin the deprecated id ( stale v8.2.16 cordova plugin a0 org. opacne.cordova.contaets Tt 1s 2150 possible to install via repo wet directly ( unstable » condova plugin a tetps:/Jatthucon/apcte/eordova-plaginecontacts. gst < » iOS Quirks 9 ‘Since iOS 10's mandalory lo ade a NsContactsUsagedescription entryin the infoplis hscontactsvsagebeserintion describes the reason thatthe app accesses the users contacts. When the system prompt the ser Lo allow access. this string is displayed as part of the dialog box. To ad ths entry you can pass the variable CONTACTS USAGE_BESCATETION on plugin instal, Intpsufcordovaapache.orgidocsien/7 xreferencelcordova-plugin-contacts! ans ‘110112023 18:08, Contac - Apache Cordova Example: cordova plugin add coréove-plugin-contacts ~-vardable CONTACTS_USAGE_DESCRIPTIONe"your usage message’ Ir you don't pass the variable, the plugin wil add an empty st Firefox OS Quirks & ing as value, Croate wrw/manifest webapp as described in Manifest Docs thtips /dovelopermozilaorg/en- US/Aops/ Developing/Manifest Add relevant errisions. There is also a need lo change the wobape type to ‘prvleged Manifest Does thitos//developer mozilla org/en-US/Apps/Developing/Marifest#lypel. WARNING: Al privileged apps enforce Content Security Policy t application in another way “permissions: rantacts": { Windows Quirks & Prior to Windows 10: Any conlacts returned from #ind and mnodify thom, find method availaole only on Windows Phon 5 //developer mozilla org/en-US/Apps/CSP) which forbids inline script. pick 1 81 devices, ize your tact methods are readonly, so your application cannot ‘Windows 40 and above: Conlac's may be saved and wil be saved to app-local contacts storage, Contacts may also be doletod Windows 8 Quirks & ‘Windows 8 Contacts are readonly. Via the Cordova API Conta cls are not queryable/searchable, you should in the user to pick a contact as a call to contactspickContact which will open the People’ app where the user must choose a contact Any Contacts retumed are readoniy, so your application cannot mi navigatorcontacts & Methods & + navigatorcontacts.roato + navigatorcontacts find + navigato-contactspickContact Objects 6 + Contact + ContactName + ContactFietd + Contactadsress + ContactOrganizaton + ContactFindOptions + Contactérror + ContactFielctType navigatorcontacts.create & “Tho navigator.contacts.create mothod ssynchronaus, and ‘This method does not -etain the Cont objectin the de contact.save method, Supported Platforms 6 + Android + BlackBerry 10 + Firefox 0S + ios + Windows Phone 8 Example $ hitpsicordova.apache.orgidocs/en/.»referencelcordova-plugin-contacts! joi them, retusa now contact abject, Contacts database, for which you need to invoke the ‘110112023 18:08, ‘Contacts - Apache Cordova (ossphayane’ “Test User" D)5 navigatorcontacts.ind ‘The navigator.contacts.find method executes asynchronously. querying array of contact objects. The resulting objects are passed to the con contactSuccess parameter © device contacts database and retuming an suecess callback function specified by the ‘The eontaetFields parameter specifi the folds to be used asa search qualifier A zor Jongth contactFields parameter is invalid and results in Contacttrrer. IWALIO_ARGUMENT_ERROR .A contactFields value of "** searches all contact fields. ‘The contactFindOptions ter string can be used as a search iter when querying the contacts database. I provided, a case: insensitive, partial value match is applied to each field specified in tne contactFields parameter If there's a match for any of the specified folds the contact is returned. Use contactFindOptions desiredFields parameter to control which contact properties must be returned back ‘Suppoted values for both contactFields and contactFindOptions desiredFields parameters are enumerated in contactFieletype object Parameters & + contactFields: Contact feds to use as.a search qualifier (OOMStingll [Required] + contactSuccess: Success callback function invoked with the array of Contact objects returned from the database. (Requirect + contactError Error callback function, invoked when an errr eccurs. [Optional + contactFindOptions: Soarch options to fltor navigatorcontacts. [Optional Koys include ® filter The search sting used to find navigatorcontacts. (DOMStrng) (Default: **) © multiple: Dete:mines i the fnd operation returns multinle navigatorcontacts,@oolean (Default: false ) © desiredFields: Contact felds to be returned back If specified the resulting Contact object only features values for these fields. (OOMStringl [Optional © hasPhoneNumberiAndroid only! (@oolean) (Default: False) ‘ters the search to only return contacts witha phone number informed. Supported Platforms 6 + Android + Blackéierry 10 + Firefox 0S + ios + Windows Phone 8 + Windows (Windows Phone 8: and Windows 10) Example & function onsuecess(eontacts) { sleet(founé "contacts. lenath ¢ © contacts. "3s faction onsrrer(corsacteren) ( alert (antoaet")5 11 Find aL. contacts with *80b" én ony name Field war options = new ContactFtndoption(): var Htetds navigator contacts. ielsTypedisplayare, navigator. contacts #ieype. ane]; ravigator-contacts.flna( fields, orsuccess, enteror, options) Type. Windows Quirks & hitpsicordova apache. orgidocs/en/.sreferencelcordova-plugin-contacts! ‘110112023 18:08, ‘Contacts - Apache Cordova + _eontact#ielas__ Is not supported and willbe ignored, ¢né method will always attempt to match the name, email address, or phone number of 8 contact. navigatorcontacts.pickContact & ‘The navigator.contacts.pickcontact method launches the Contact Picker to select a single contact. The resulting object Is passed tothe contactsuccess callback function specified by the eontactSuccess parameter. Parameters & + contactSuceess Success callback function invoked with the single Contact object. Required + contactError Error callback function, invoked when an errr occurs. IOptionall ‘Supported Platforms 6 + Andoid + 10s + Windows Phone 8 + Windows Example & ravigator contacts. pletcontact(fanction(contae®){ console 9g("The Following contact as been selected:* + 350 stringhéy(contact)): Dofenctioner oneolesiog( error: ° + err) Ds Android Quirks § ‘This plugin launches an external Activity fr picking contacts, Soe the Android Lifecycle Guido Untp//cordove apache.org/docs/en latest/quide/ platforms android /incex himlflfecycle-quide) for an explanation of how this afects your application. Ifthe plugin retumsits result nthe resure evert, then you must frst wrap the returned object in 2 Contact object before using i. Here isan example: function oneseve(resunetvent) ( “f(resunetvent-pendignesutt) { ¢(corcrotventpenaingserultpluginstatur = °OC") { var contact» navigator. cortactscreate(resmetertpentinghesul® rest); accesscanback(eantaes) pane ( ‘atlcalinak (resuotvontpenctngtesut rel); > Contact & ‘The contact object reoresents a user's contact. Contacts can be croaked. stored. or removed from the devico contacts database, Contacts can also be retrieved tindivicually orin bulk! from the database by invoking the navigator contacts. find method. NOTE: Not all ofthe contact flelds lsted above are supported on every device platform. Please check each platform's Quirks section for details Properties + id A globally unique identifier ©OMSting! + dlsplayName The name ofthis Contact, suitable for csplay to end users. (DOMString) + ame. An object containing al compononts ofa persons name. ContactName) + slekname: A casval name by which to address the contact (OOMStrng) + phoneNumbers An aray ofa the contac’ phone numbers. (Contacte + emails An array of altho contact’ email adcressos. (Contacte) + addresses: An array ofall the contac’sacdresses (ContactAlessh) + ms: An array of al the contact's IM addresses. (ContactFeta Intpsifcordova.apache.orgidocsien/7 xreferencelcordova-plugin-contacts! ans. ‘017023 18:05 Contacts - Apache Cordova + erganizations An aray of al the contacts organizations. (ContoctOxganizationt) + birthday: The bithday of the contact ote) + ote: Anote about the contact DOMSting! + photos: An aray ofthe contac’s photos. CantactFell) + categories: An array of al the user-defined categories associated with the contact (ContoctFelal + urls: An aray of web pages associated with the contact. (ContactFietal) Methods & + clone Roturns.anow contact object that Isa deep copy of the calling object. with the 1d property sotto nul. + remove: Removes the contact from the device contacts database, otherwise executes an errr ealback with a contacterrer object. + save. Saves a new contac lo the dvice contacts database, or dates an existing contac fa contact withthe same id already exists. Supported Platforms 9 + Amazon Fire 05 + Android + BlackBerry 10 + Frofox oS + ios + Windows Phone 8 + Windows Save Example & focuser suse) & function onerror(contactteror) ¢ slere ("error =" + cotacterrorcode): % U1 create 4 nen contact object var contact = avigator.cortacts.create(d ontactdisoLayiae = “Planter”; contact.ntexnane = “Planter”; U1 specify both to support alt devices 17 popstate sone Fletas or mane = new Contsct¥ane(}5 11 sove to device contact-save(arsuccess,onteror): Clone Example & 11 clone the contact ebsect var clone = contact. elene(): ‘console Log(Original contact nane = * 6 contact, ane. ghvemane)s angele 1og(*Cloned contact nane = ~ + Clone.rane.giversare) Remove Example $ fanction onsuccess) alert (“Reneval Success") » function onerrorconsactéeror) ( alert ("error =" + cotactérror code); % U/ remove the contact fron the device ont act-rovove(onssces5, arr); Intpsufcordova.apache.orgidocsien/7 xreferencelcordova-plugin-contacts! 53 ‘110112023 18:08, ‘Contacts - Apache Cordova Removing phone number(s) from a saved contact & 1/ exonp.e to create @ contact with 3 phone eunbers and then remove 122 phone oimbers, Tels expla ts for illustrative purpose only ar nycontact = navigator-contarts creste(("displaytane”: "Test User") pronehuners} = nw contactFielé(‘wor, 768-885-1234", Fale); Pronehinoes[1] = mw ContactFielo(‘sbile", "998-555-5439", trues // preferred muster Protehuners[2} = ew ContactFiele(“hone, 203-855-7008", fase; syconeace-save( function (contact o5)} { ‘ar coreaetdnjiaodsty = coreaetobj-clene() Contact_obj.cenovel Funetien()¢ ‘var piotehunsers = [contactobsTotbdtey.phoneuners[@] antactonsTaodsty save (Function) forse Log" Done"); 3, fanettonomor)( Console log Not able to save the cloned objects * + eorords » Dy Faneton(contacterrer) onsale iog("antact Ronove Speraien failed: * + contactEerar; ps Android 2.X Quirks ¢ + categories: Not supported on Android 2X devices, returning nut BlackBerry 10 Quirks ¢ + Assigned by the device when saving the contact FirefoxOS Quirks 6 + categories: Partially supported, Fields pref and type are reluming oul + ims: Not supported + photos: Not supported iOS Quirks 9 + displayName: Not supported on iOS. returning nul uniess there's no contactNane specified. in which case it returns the compostte name, nickname or “*, respectively + birthday: Must be input asa JavaScrint bate object the same way its returned, + photos: Retuinsa 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 support ing mul Windows Phone 8 Quirks & + displayName: When creating a contact, the value provided forthe display name paramelerdifers from the display ame retsleved when fining the conta + urls: When creating a contact, users can input and save more than one web address, but only one is avalable when searching the contact, + phoneNumbers: The pref option isnot supporled The type snot supported in a find operation. Orly one phoneNurber fs allowed for each type, + emails The pref option isnot supported, Home and personal references same email entry Only one entry is allowed for each te. + addresses: Supports only work, and hore/personal type. Tre home and personal type reference the same address lente Only one entry is allowed for each type. + organizations: Only one is allowed, and does not support the pref ype, and department attributes + note: Not supported, returning mutt + ims: Not supported, returning mult hitpsicordova apache. orgidocs/en/.sreferencelcordova-plugin-contacts! ‘110112023 18:08, ‘Contacts - Apache Cordova + birthdays: Not supported, returning mutt + categories: Not supported, retuming null + remove: Method isnot supeor Windows Quirks ¢ + photos: Returns a Fle URL to the image, whichis stored in the application's temporary directory. + birthdays: Not supported, returning nu! + categories: Not supported, returning au + remove: Method is only supported in Window's 10 or above, ContactAddress & “The contactaddress object stores the properties ofa single address ofa contact A contact object may inlude more than cone adress ina contactadcress{] aay Properties & + pret Selo true this contactaddress conlans lhe user's preferred value. boolean) + type: string incicating wnat type of fold his is. home for example. (DOMStrng! + formatted Tho full addoss formatted for elsplay (OOMSting! + streotAddress The ful sret adress. (DOMString) + locality. The ely 0 locally. (DOMStrng) + region The state or region. (DOMSng! + postalCode The zipcode or postal code. (DOMString) + country: Tho countzy name. ‘GOMSting! Supported Platforms & + Amazon Fie OS + Arco + BlackBerry 10 + Firefox os + 10s + Windows Phone & + Windows Example & hitpsicordova.apache.orgidocs/en/.»referencelcordova-plugin-contacts! ‘110112023 18:08, ‘Contacts - Apache Cordova 11 dsplay the astress tnforeation for aL. contacts faction onsuccess(contscts) { for (vor 12 8; Le contacts. 2engths 144) { for (var j= 0; j ¢ contacts[s]. addresses Lengths $441 lent ret ‘ contacte[A]-aedeeses( )- pret sows “Type . aadresses)-type Sons “formatted: + Sedresres[j}-foreatted "Wn" + Street Aderess: “4 contacte[i] aedreses(])-streetaadrast 6 "6 stocality: "+ contacts[t}.acresses(H)-locality “Ant + stegion: + Sedresses[J] region "Ww + porcal cage: * adresrer[j]-portsleade "Wn" + ote : ‘udresses[J) country); faction onsrror(consscterer) { slers(‘onteror") 5 var options = new Contacttinenptions(): var etter = ("aspiayNane", “aedresses*}s ravigator-contaets-fina((iiter, orsuecess, enéerar, epttons) Android 2.X Quirks ¢ + pref Not supported, tuming false on Android 2X devices. BlackBerry 10 Quirks $ + prof Not supportec on BlackBerry dovicesreturning false + type: Partially supported. Only one each of Work and Home type addresses can be stored per contact. + formatted Partially supported. Retums a concatenation ofall BlackBerry address fields + streethddress: Supported, Returns a concatenation of Blacklerry aedressi and aedress2 adress fds + locality Supported. Stored in BlackBer city acres fe + region Suoported. Stored in BlackBerry stateProvinee adress fel. + postalcode Supported Stored in BlackBerry zipPostal adctess field + country: Suporte. FirefoxOS Quirks & + formatted: Currently not supported iOS Quirks 9 + pref Not supported on OS devices. returning #alse + formatted Currently not supported. Windows Quirks ¢ + pref. Not supported ContactError & e Contactéeror objects retumed to the user through the contactErren callback function when an error occurs. Properties + code One ofthe predefined eror codes listed below Constants 6 + contactéeror.umcion_eRRoR (code a} + contactéeror.IWALID_ARCUMENT_ERROR (code 2) + contactéeror TIMEOUT_eRROR (code 2} + contactEeror.PENDING_aPERATION ERROR (code 3) hitpsicordova.apache.orgidocs/eni7.»referencelcordova-plugin-contacts! ‘110112023 18:08, ‘Contacts - Apache Cordova + contactérror. 10 ERROR (code 4) + contactEeror.NOT_SUPPORTED_ERROR (code 5) + contactEerorgPERATION_CANCELLED_eRROR (code 6) + contactEeror PERHZSSz04_DENIED_ERROR (code 20), ContactField & ‘The Contact#iel4 object is a reusable component that represents. tac elds genericaly.€acn Contact#ield object contains a value. type.and pref property. A Contact object slores several properties in ContactFieldf) arrays, such as phone numbers and emall addresses, In mostinstances, there are no pre-determined values fora contactField object's type attribute, For example, @ phone number can specify type values of heme, work, mobil, Phone, or any other value that is supported by a particular device platform's contact database, However for the contact photos fc. the type field indicates the format of the returned image turLwhen the value atribute contains @ URL to the pholo image, or bose64 when the value contains a baseSé-encoded image string. Properties + type: A string that indicates what type of fee this is. home for examle. DOMStrng) + value: The value of the fel, such asa phone number or email adress (OOMStrng + pref. Set to true ifthis contactrield contalns the user's preferred value. boolean) Supported Platforms & + Amazon Fre 05: + Android + BlackBerry 10 + Firofox 0S + ios Windows Phone & + Windows Example & 11 create 9 nou svigator-contacts.create(): Provehinoers[e] = new ContactFicle(‘nork’ 232-888-2234", false Dronenanoers1} = new CortactFielé(‘nblle’y 917-885-5852", true); // preferred nanber Prorehanser[2] = ew ContactFielu(“hone", 203-858-7080", False) 11 sove the contact antact-s2v00, Android Quirks 8 + pret Nol supporec. eturring fatse BlackBerry 10 Quirks § + type: Partially supported, Uses Yor phone rumors. + value. Suppored. + prof Not supported, otumning false iOS Quirks ¢ + pref Not supportec, returning fase Windows Quirks ¢ + pref Not supported, ming fase ContactName & Contains diforont kinds of information about a contact objoc’s name. hitpsicordova apache. orgidocs/en/.sreferencelcordova-plugin-contacts! ‘017023 18:05 Contacts - Apache Cordova Properties + formatted: Tho compicte name of the conta (oomstring? + familyName The contact’ family name. (0OMString) + givenName: The contact’s given namo, DOMSting) + middleName: The contacts midale name. (DOMStrng) + honorifePrefx The contacts prefix (examale Mr or Del OOMString) + honorifeSuffix The contac’ sufix (example Esq). (DOMStng! Supported Platforms 6 + Amazon Fire OS + Android + Blackerry 10 + Firefox 0S + ios + Windows Phone 8 + Windows Example & function onsuccess(eantacts) { for (oar i+ 8; 1 ¢ contacts 2engths 148) ( alert Foractes: + cortactst] tame formatted + “at + sly Nove: ~ + coreacte[s] rane fantiiine "Wa" + ‘sven Hane: "+ conaete[s)urane_piversore 4 “\n" 6 ‘ consaete[s).nane.tiadietone 8 nt 4 consacts[). ane forarifiesufeix ¢ "Ve" + » coneaeta[s] rane honor tesufa) function onerrortcontactteror) ( alert (“oneeror!) var options = ne Contact indbption() ister = ["dtsplaytane”, “rane"]: Tavigntor-contacts.tina(¢Siter, onsuecers, onéeror, options) Android Quirks & + formatted: Partaly supported, and read-only. Returns a concatenation of honoriFcPrefix. glvenNane niddlekone. BlackBerry 10 Quirks $ + formatted Partially suppor: Retuins a concatenation of BlackBerry frstName anc tastName folds + familyName Supported Stored in BlackSerry LastName fed + alvonName: Supported, Stored in BlackBer frstName fold + middleName: Not supported returning out + honorifePrefix Not supported returning ast + honerifleSutfix Not supported, ing mul FirefoxOS Quirks § + formatted. Partally supported, anc read-only Returns a concatenation of honerificrrefix. givenNane.. nidleNane. fanilytane and honor fiesuf fix iOS Quirks 6 + formatted. Partally supportes. Rel snsiO$ Composite Name, butis read-only, Windows Quirks ¢ hitpsicordova apache. orgidocs/en/.sreferencelcordova-plugin-contacts! 103 ‘110112023 18:08, ‘Contacts - Apache Cordova + formatted This the only name property. andis identical to displaytane. and nicknane + familyName not supported + givenName: not supported + middleName: not supported: + honorficPrefix not supported honorifesuix not supported ContactOrganization & ‘The contactorganization object stores a contact's organization properties. A contact object stores one or more Contactorgarization objects in an array Properties & + pref. Sotto ue if this Contaetorgantzation contains the user's preferred value. tbeolean) + type: A string that indicates what type of field this is, home for example. OOMString) + name The name of the organization. (DOMSring! + department: The department the contract works for (DOMStrng) + ttle: The contacts ttle atthe organization. (OMStrng) Supported Platforms + Android + BlackBorry 10 + Firofox oS + 105 + Windows Phone & + Windows (Windows 84 and Windows Phone 84 devices on Example & function onseecrs(eantacts) { for (var £2 0; 1 contacts Zength; 144) { for (var j = 0; J € contacts[s]-organizations Lengthy $+) { tert (Pref “contactel{].organizations|J]igre# 6 *\at 6 ype 4+ comtacts[t]-organtzations|sitye + “Mat + see: ‘ conssts[$].arganssattone(SJ.aare Wn" + separenent: * + contacts] onganiaations[3] departnant ©

You might also like