I know how to retrieve a value from a textfield that a user has inputed, however, I want to be able retrieve the text thats outputed from the following code:
var message = url;
document.getElementById('result').innerHTML = message;
Essentially I want to store into Parse a shorten URL, where the URL is generated from the document selected in Google Drive, and then that URL is display on screen to the user, and thats the URL I want to grab to shorten.
Below is the entire code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>upload</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = url;
document.getElementById('result').innerHTML = message;
}
var longUrl=message;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<div id="output">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
In particular, this where I attempt to shorten the URL to store into Parse:
var longUrl=message;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
Any help would be greatly appreciated
Update:
Please try out this code. It shortens a url from the input value you insert. In the sense that you enter example yahoo.ca in the input field, and once you hit convert it shortens it into a url and store in parse. This works succesfully, but I wanted to integrate that into my code where the url is derived from the url that is generated from the item the user has selected from their google drive:
<html>
<head>
</head>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<script type="text/javascript">
function makeShort()
{
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
Related
I am receiving the following error:
Uncaught TypeError: Cannot read property 'urlshortener' of undefined
I am essentially trying to store into parse a url generated from google drive that has been shorten.
Below is the entire code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>upload</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult
);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = url;
document.getElementById('result').innerHTML = message;
}
var longUrl=url;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<div id="output">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
In particular, this where I attempt to shorten the URL to store into Parse:
var longUrl=url;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
Update:
Please try out this code. It shortens a url from the input value you insert. In the sense that you enter example yahoo.ca in the input field, and once you hit convert it shortens it into a url and store in parse. This works succesfully, but I wanted to integrate that into my code where the url is derived from the url that is generated from the item the user has selected from their google drive:
<html>
<head>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<script type="text/javascript">
function makeShort() {
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
}
function load() {
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"></script>
</head>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
I dug through your example and tried to see what is going on, but I opted to start fresh and try to accomplish this in a simple way. I see that you are using Angular, so I made a little fiddle to try and shorten the url to this question.
The main issue I think, is that you need to generate a new key and follow the configuration steps. I did so in minutes and it worked fine. Be sure to choose the api you want (urlshortener) in your dashboard!
Here is the link I was able to generate http://goo.gl/15yWwP
function googleOnLoadCallback() {
var key = '{ YOUR KEY }';
var apisToLoad = 1; // must match number of calls to gapi.client.load()
var gCallback = function () {
if (--apisToLoad == 0) {
//Manual bootstraping of the application
var $injector = angular.bootstrap(document, ['app']);
};
};
gapi.client.setApiKey(key);
gapi.client.load('urlshortener', 'v1', gCallback);
}
<script src="https://apis.google.com/js/client.js?onload=googleOnLoadCallback"></script>
And inside my shorten() function
var request =
gapi.client.urlshortener.url.insert({
'longUrl': '{ YOUR LONG URL }'
});
request.execute(function(response) {
console.log(response.id);
});
JSFiddle link
I unexpectedly received the following error through the debugger when trying to execute parse.
Uncaught ReferenceError: Parse is not defined
I am pretty sure its well defined so not sure where the error derives from.
Essentially what happens here is that a long url gets converted into a short url using google url shorten and then parse grabs the shorten url and stores it.
<html>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
In particular, below is the conversation happens, and where I try to store the url to parse:
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
Maybe you have this in another file but where is your code where you reference Parse http://www.parsecdn.com/js/parse-1.3.5.min.js ?
Maybe you are missing that and that's why you get the error.
I would like to store a URL as a string into parse.
In particular, user select an item from Google drive using the Google Drive Picker, and then a URL is produced. I want to take that URL and store it into parse under a class named "Scan".
Let me better elaborate in code:
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
I have generated the url through
url = doc[google.picker.Document.URL];
and where the url is displayed as a string on the website through the following lines:
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
All i want is to store that url into parse, however, not sure how to workout this code and inserted in the my google drive picker select code as shown below:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>eSnail Scan Upload Part 2</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
</script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
Any help would be greatly appreciated.
Update 2: Below is a code that has tries to integrate parse with my initial code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>eSnail Scan Upload Part 2</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("Name", url);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
</script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
In particular this section,
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
}
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("Name", url);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
under your
Parse.initialize("ID", "ID");
try:
var PDFUploadObject = new Parse.Object.extend("Scan");
var PDFUpload = new PDFUploadObject ();
PDFUpload.set("Name",url);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
it always says The page you requested is invalid.
how can i fetch the contacts with javascript using google contacts api
i have valid scope and Client ID
google.load('gdata', '2.x');
debugger
google.setOnLoadCallback(function () {
if (window.location.hash == "") {
if (!checkLogin()) {
logMeIn();
} else {
var feedUrl = "https://www.google.com/m8/feeds/contacts/default/full";
query = new google.gdata.contacts.ContactQuery(feedUrl);
query.setMaxResults(5000);
myService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
myService.getContactFeed(query, function (result) {
document.cookie = "g314-scope-0=";
window.opener.parseGmailContacts(result.feed.entry);
close();
}, function (e) {
alert(e.cause ? e.cause.statusText : e.message);
});
}
}
});
function logMeIn() {
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.login(scope);
}
function logMeOut() {
google.accounts.user.logout();
}
function checkLogin() {
scope = "https://www.google.com/m8/feeds/";
var token = google.accounts.user.checkLogin(scope);
return token;
}
i think there is something wrong with
var token = google.accounts.user.checkLogin(scope);
return token;
token retuns ""(empty value here), how can i get the value of the token to get the contacts , plz help
I ran into the same problem, I solved it by first retrieving an access token, and then call the API directly. This is because the javascript api (gapi) does not support retrieving google contacts.
Since it was quite the hassle, I wrote a blogpost about it here: https://labs.magnet.me/nerds/2015/05/11/importing-google-contacts-with-javascript.html
Basically this is how I solved it:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
var clientId = 'your Client ID';
var apiKey = 'Your API Code';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$(document).on("click",".googleContactsButton", function(){
gapi.client.setApiKey(apiKey);
window.setTimeout(authorize);
});
function authorize() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
});
}
}
</script>
<script src="https://apis.google.com/js/client.js"></script>
<button class="googleContactsButton">Get my contacts</button>
</body>
</html>
Try using components my friend. Life's gonna be easier and prettier.
http://googlewebcomponents.github.io/google-contacts/components/google-contacts/
For fetching list of contacts using Google plus use this :-
<script src="https://apis.google.com/js/client.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
function auth() {
var config = {
'client_id': 'OAUTH_CLIENT_ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
console.log(JSON.stringify(data));
}
});
}
In the HTML Body :-
<button onclick="auth();">GET CONTACTS FEED</button>
The output will have as a field with the contact containing the phone number.
Make sure to get the client id from google developer console with proper redirect uri.
I had slight issue with popup flashing every time the button is clicked. Adding the snippet below to Wouters solution will stop the popup window from flashing.
function authorize(){
if($scope.authorizationResult){
handleAuthorization($scope.authorizationResult);
}else{
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate:false}, handleAuthorization);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
// Developed By: Garun Mishra.
var clientId = 'Your Client Id';
var apiKey = 'Your Api Key';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$(document).on("click", ".getGmailContact", function () {
gapi.client.setApiKey(apiKey);
window.setTimeout(authorize);
});
function authorize() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function (response) {
//process the response here
//console.log(response);
var entries = response.feed.entry;
var contacts = [];
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var contact = [];
//console.log(contactEntry);
// Get Full Name.
if (typeof (contactEntry.gd$name) != "undefined") {
if (typeof (contactEntry.gd$name.gd$fullName) != "undefined") {
if (typeof (contactEntry.gd$name.gd$fullName.$t) != "undefined") {
contact['name'] = contactEntry.gd$name.gd$fullName.$t;
}
}
}
// Get Phone Number
if (typeof (contactEntry['gd$phoneNumber']) != "undefined") {
var phoneNumber = contactEntry['gd$phoneNumber'];
for (var j = 0; j < phoneNumber.length; j++) {
if (typeof (phoneNumber[j]['$t']) != "undefined") {
var phone = phoneNumber[j]['$t'];
contact['phone'] = phone;
}
}
}
// get Email Address
if (typeof (contactEntry['gd$email']) != "undefined") {
var emailAddresses = contactEntry['gd$email'];
for (var j = 0; j < emailAddresses.length; j++) {
if (typeof (emailAddresses[j]['address']) != "undefined") {
var emailAddress = emailAddresses[j]['address'];
contact['email'] = emailAddress;
}
}
}
contacts.push(contact);
}
// To Print All contacts
console.log(contacts);
// You can fetch other information as per your requirement uncomment the given line and read the data.
//console.log(entries);
});
}
}
</script>
<script src="https://apis.google.com/js/client.js"></script>
<button class="getGmailContact">Get My Gmail Contacts</button>
</body>
</html>
I am using the phonegap 2.9.0 and trying to implement twitter for an app i am building for ios.
i am following this tut but havent gotten much luck with it . implemented child browser using visit and since its cordovo.plst is deprecated added the following line in config.xml
<feature name="ChildBrowserCommand">
<param name="ios-package" value="ChildBrowserCommand" />
</feature>
in my index.html file
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="jsOAuth-1.3.6.min.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
<script type="text/javascript">
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var root = this;
cb = window.plugins.childBrowser;
if (!localStorage.getItem(twitterKey)) {
$("#loginBtn").show();
$("#logoutBtn").hide();
}
else {
$("#loginBtn").hide();
$("#logoutBtn").show();
}
if (cb != null) {
cb.onLocationChange = function(loc) {
root.locChanged(loc);
};
cb.onClose = function() {
root.onCloseBrowser()
};
cb.onOpenExternal = function() {
root.onOpenExternal();
};
}
}
function onCloseBrowser() {
console.log("onCloseBrowser!");
}
function locChanged(loc) {
console.log("locChanged!");
}
function onOpenExternal() {
console.log("onOpenExternal!");
}
</script>
<!--Below is the code for twitter-->
<script>
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {
consumerKey: 'CONSUMER KEy', // YOUR Twitter CONSUMER_KEY
consumerSecret: 'CONSUMER_SECRET', // YOUR Twitter CONSUMER_SECRET
callbackUrl: "http://www.textalert.com/"}; // YOU have to replace it on one more Place
var twitterKey = "twtrKey"; // This key is used for storing Information related
var Twitter = {
init: function() {
// Apps storedAccessData , Apps Data in Raw format
var storedAccessData, rawData = localStorage.getItem(twitterKey);
// here we are going to check whether the data about user is already with us.
if (localStorage.getItem(twitterKey) !== null) {
// when App already knows data
storedAccessData = JSON.parse(rawData); //JSON parsing
//options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin
// javascript OAuth take care of everything for app we need to provide just the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("USERNAME: " + entry.screen_name);
}
);
}
else {
// we have no data for save user
oauth = OAuth(options);
oauth.get('https://api.twitter.com/oauth/request_token',
function(data) {
requestParams = data.text;
cb.showWebPage('https://api.twitter.com/oauth/authorize?' + data.text); // This opens the Twitter authorization / sign in page
cb.onLocationChange = function(loc) {
Twitter.success(loc);
}; // Here will will track the change in URL of ChildBrowser
},
function(data) {
console.log("ERROR: " + data);
}
);
}
},
/*
When ChildBrowser's URL changes we will track it here.
We will also be acknowledged was the request is a successful or unsuccessful
*/
success: function(loc) {
// Here the URL of supplied callback will Load
/*
Here Plugin will check whether the callback Url matches with the given Url
*/
if (loc.indexOf("http://www.textalert.com/?") >= 0) {
// Parse the returned URL
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if (y[0] === 'oauth_verifier') {
verifier = y[1];
}
}
// Here we are going to change token for request with token for access
/*
Once user has authorised us then we have to change the token for request with token of access
here we will give data to localStorage.
*/
oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier=' + verifier + '&' + requestParams,
function(data) {
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
}
$('#oauthStatus').html('<span style="color:green;">Success!</span>');
$('#stage-auth').hide();
$('#stage-data').show();
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
// Saving token of access in Local_Storage
var accessData = {};
accessData.accessTokenKey = accessParams.oauth_token;
accessData.accessTokenSecret = accessParams.oauth_token_secret;
// Configuring Apps LOCAL_STORAGE
console.log("TWITTER: Storing token key/secret in localStorage");
localStorage.setItem(twitterKey, JSON.stringify(accessData));
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
console.log("TWITTER USER: " + entry.screen_name);
$("#welcome").show();
document.getElementById("welcome").innerHTML = "welcome " + entry.screen_name;
successfulLogin();
// Just for eg.
app.init();
},
function(data) {
console.log("ERROR: " + data);
}
);
// Now we have to close the child browser because everthing goes on track.
window.plugins.childBrowser.close();
},
function(data) {
console.log(data);
}
);
}
else {
// Just Empty
}
},
tweet: function() {
var storedAccessData, rawData = localStorage.getItem(twitterKey);
storedAccessData = JSON.parse(rawData); // Paring Json
options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login
// javascript OAuth will care of else for app we need to send only the options
oauth = OAuth(options);
oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
function(data) {
var entry = JSON.parse(data.text);
Twitter.post();
}
);
},
/*
We now have the data to tweet
*/
post: function() {
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://api.twitter.com/1/statuses/update.json',
{'status': theTweet, // javascript OAuth encodes this
'trim_user': 'true'},
function(data) {
var entry = JSON.parse(data.text);
console.log(entry);
// just for eg.
done();
},
function(data) {
console.log(data);
}
);
}
}
function done() {
$("#tweet").val('');
}
function successfulLogin() {
$("#loginBtn").hide();
$("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();
}
function logOut() {
//localStorage.clear();
window.localStorage.removeItem(twitterKey);
document.getElementById("welcome").innerHTML = "Please Login to use this app";
$("#loginBtn").show();
$("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();
}
</script>
<!--Code for Twitter ends here-->
</head>
<body onload="onBodyLoad()">
<h4>Oodles Twitter App</h4>
<table border="1">
<tr>
<th>Login using Twitter</th>
<th>
<button id="loginBtn" onclick="Twitter.init()">Login</button>
<button id="logoutBtn" onclick="logOut();">Logout</button>
</th>
</tr>
<tr id="tweetText" style="display:none;">
<td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
</tr>
<tr id="tweetBtn" style="display:none;">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
</body>
</html>
On clicking the login button i get ERROR: [object Object] this error any help would be much appreciated thankyou
hi use TWITTER plugin for Phonegap IOS check Link