Skip to content

Instantly share code, notes, and snippets.

@khankuan
Created January 9, 2014 07:12
Show Gist options
  • Save khankuan/8330540 to your computer and use it in GitHub Desktop.
Save khankuan/8330540 to your computer and use it in GitHub Desktop.
Javascript get user Google contacts
<script src="https://apis.google.com/js/client.js?onload=gapiLoad"></script>
<script>
function gapiLoad() {
gapi.client.setApiKey('YOUR_API_KEY'); // app api-wide client api key
getGoogleContactEmails(function(result){
console.log(result);
});
}
function getGoogleContactEmails(callback) {
var oauth_clientKey = 'YOUR_OAUTH_KEY'; // replace with your oauth client api key
var firstTry = true;
function connect(immediate, callback){
var config = {
'client_id': oauth_clientKey,
'scope': 'https://www.google.com/m8/feeds',
'immediate': immediate,
};
gapi.auth.authorize(config, function () {
var authParams = gapi.auth.getToken();
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?max-results=10000',
dataType: 'jsonp',
type: "GET",
data: authParams,
success: function (data) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(data,"text/xml");
var entries = xmlDoc.getElementsByTagName('feed')[0].getElementsByTagName('entry');
var contacts = [];
for (var i = 0; i < entries.length; i++){
var name = entries[i].getElementsByTagName('title')[0].innerHTML;
var emails = entries[i].getElementsByTagName('email');
for (var j = 0; j < emails.length; j++){
var email = emails[j].attributes.getNamedItem('address').value;
contacts.push({name: name, email: email});
}
}
callback(contacts);
},
error: function (data) {
if (firstTry)
connect(false, callback);
firstTry = false;
}
})
});
}
connect(true, callback);
}
</script>
@smartjj
Copy link

smartjj commented Apr 28, 2015

Thank your coding. May I ask how to get the phone number and the address of the contacts' ? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment