Add contacts to Google Contacts' main Contacts

2020-04-19 05:44发布

问题:

I'm using the GAS code bellow to add a new contact into Google Contacts (https://contacts.google.com/):

var contact = ContactsApp.createContact('Bbbb', 'Cccc', 'mymail@mails.com').addUrl(ContactsApp.Field.WORK_WEBSITE, 'https://sites.google.com/site/diccionarioie');

The code works perfectly but for a single detail: it adds the new contact to a hidden list and not to the main or visible «Contacts» list.

I know it works because when I use the lookup box to search for the newly created contact it's there, in the «Other contacts» list. I need it to be created in the main «Contacts» list from the beginning, otherwise I would have to do it manually using the «Add to contacts» icon with every contact created (I'm planning to add some thousands of contacts.)

Thanks.

回答1:

For me, I have to add them to the ContactGroup named System Group: My Contacts.

function finishAddingContact(contact) {
  var mainGroup = ContactsApp.getContactGroup("System Group: My Contacts");
  if(mainGroup)
    mainGroup.addContact(contact);
}

Note that getContactGroup(string) is an exact name match.

I recommend inspecting your ContactGroups for system groups, and then selecting the appropriate one from that list. It's probably the one with the most contacts in it:

function inspect() {
  var groups = ContactsApp.getContactGroups();
  for(var g = 0; g < groups.length; ++g) {
    if(groups[g].isSystemGroup()) {
      Logger.log(groups[g].getName() + ": " + groups[g].getContacts().length + " members, id=" + groups[g].getId());
    }
  }
}


回答2:

Thanks a lot tehhwch.

I used your second code to get the right group ("System Group: My Contacts"), and then:

var contact = ContactsApp.createContact('Wunder', 'Bar', 'excellent@help.com');
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(contact);

It works, and the contact is immediately visible in my Android device.