Google-apps – How to download all directory contacts

data-liberationgoogle-appsgoogle-contacts

How do I export all the contacts from the directory? I can not select all of the contacts, only 250 at a time (which would be time consuming). Also, the more button is grayed out, which prevents the obvious route.

Is there a way to get all the contacts? Has someone setup a script to scrape it, if there is no official functionality?

Best Answer

Apologies for the late answer, but I have recently been wanting to accomplish this too.

I used the latest version of Google Contacts at the time of writing, and the density layout of "Compact" (not the default "Comfortable"!).

I then used the column order of

  1. Name
  2. Job title & company
  3. Email
  4. Phone number
  5. Labels (I did not have any so I could not test it)

This worked with the script I wrote. It saved all the contacts as a hashmap to a global variable at window.exportedContactsStorage.

With large organisation directories, this script may take too long to complete, or may suffer from memory overflows.

In the future, if I have enough time, I may write a better scraper that sends each entry to an HTTP server running on localhost, effectively solving all memory overflow problems.

For now, this is the script I am using. You may (will) need to change it if you want to use it with your client.

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, 4000);
    });
}

window.exportedContactsStorage = new Set();
window.scroller = document.querySelectorAll('.ZvpjBb.C8Dkz')[0].parentElement.parentElement.parentElement.parentElement;
while (scroller.scrollHeight - scroller.scrollTop > 400) {
    for (let element of document.querySelectorAll('.ZvpjBb.C8Dkz')[0].querySelectorAll('.XXcuqd')) {
        if (element.firstChild.childNodes.length == 1) {
            break;
        }
        let name = element.firstChild.childNodes[1].innerText;
        let job = element.firstChild.childNodes[2].innerText;
        let email = element.firstChild.childNodes[3].innerText;
        let phone = element.firstChild.childNodes[4].innerText;
        window.exportedContactsStorage.add(JSON.stringify({'name': name, 'job': job, 'email': email, 'phone': phone}));
    }
    scroller.scrollTo({
        top: scroller.scrollTop + 400,
        behavior: 'smooth'
    });
    console.log(
        'Completed iteration;',
        scroller.scrollTop.toString() + '/' + scroller.scrollHeight.toString() +
        ' = ' + (scroller.scrollTop / scroller.scrollHeight * 100).toString() + '%'
    );
    await sleep(4000);
}

And to extract the variable to a file, use JSON.stringify(Array.from(exportedContactsStorage)).