Search code examples
javascriptandroidcordova

get contact list in JS


I want to get contact list from Android(If user open website in android). I was searching on it little bit. I found two question in stackoverflow similar to this.

  1. Obtain Contacts Permission before Navigating (Cordova)

  2. Listing phone contacts using javascript

  3. Cordova

Here what I tried.

    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);

I didn't get any error or alert message in android. When I visit the webpage in PC I got an error

Uncaught ReferenceError: ContactFindOptions is not defined at contacts.php:17

I think I am having error cause, there's no contact function in PC. I am so beginner in JS. I think Cordova must be installed in PC, I am not sure of the information also. If I have to than how can I install Cordova? I am using Debian Based Linux Distro. So, I tried

sudo apt-get install cordova

But,

E: Unable to locate package cordova


Solution

  • Are you building a mobile app with Cordova or are you just running your code in a website on Android?

    If it’s just a website: you simply can’t do what you want since the browser doesn’t provide an interface to the contact list.

    Unlike a Cordova app, which has access to the system APIs, among them the contact list API, JavaScript Code executed in a mobile browser, cannot access such APIs. The browser JS API simply provides no way.

    JavaScript code run inside a Cordova/Capacitor mobile app however can Cordova APIs which bridge the mobile’s native API to JavaScript.