Forked from khankuan/Javascript get user Google contacts
Created
August 18, 2016 08:15
-
-
Save SergeyKozlov/339b6ffab95d401faad58a941d9f9fa4 to your computer and use it in GitHub Desktop.
Javascript get user Google contacts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment