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
Related
I've been using Python and Selenium to try to automate an export process in Qualtrics. I have the web driver navigate to the login page, input my login credentials, and then navigate to the Data and Analytics page of the relevant survey. However, once I navigate to the Data and Analysis page, I'm having trouble selecting the element for the dropdown icon under the action header, which I need to click in order to export the responses.
I've tried to use this code (omitting the part where I login):
from selenium import webdriver
survey_url= {The Survey Url}
browser= webdriver.Chrome()
browser.get(survey_url)
browser.find_element_by_xpath("//div[#id='itemContext']").click()
However, I keep getting this error: NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[#id='itemContext']"}
I've tried using both the absolute (/html/body/div[6]) and the relative (//*[#id="itemContext"]) xpath given to me by inspect element, but neither worked.
This is the HTML that I see for the element:
<div id="itemContext" ng-click="removeSelf()" qmenu items="recordActions" on-select="selectRecordAction()(value,rowId, recordIndex)" class="response-context ng-scope ng-isolate-scope" style="left:1315px;top:357px">
<span ng-transclude></span></div>
Here is the HTML for the webpage:
<html ng-app="responses-client">
<head>
<meta charset="utf-8">
<title>Data | Qualtrics Experience Management</title>
<script>
(function (window) {
'use strict';
/*
* This function is used to attempt to get the initial definition before
* angular is loaded. If this fails for some reason the definition will
* still be loaded, but not via this function. See fast-definition-service.
*/
function rejectError(data, status, statusText) {
data = data || {};
window.fastDefinitionState = 'ERROR';
window.fastDefinitionError = {
status: status || 500,
statusText: statusText || 'Internal Server Error',
data: data,
config: {
method: 'GET',
url: url
}
};
}
function handleResponse() {
var status = request.status;
var data;
try {
data = JSON.parse(request.responseText);
} catch (e) {
data = request.responseText;
}
function handleSuccess() {
window.returnedDefinition = { data };
window.fastDefinitionState = 'SUCCESS';
}
if (status >= 200 && status < 400) {
return handleSuccess();
} else {
return rejectError(data, status, request.statusText);
}
}
function attemptRequest() {
request.open('GET', url, true);
request.onload = handleResponse; // Recieved response from server
request.onerror = rejectError; // Connection to server error
request.send();
window.fastDefinitionState = 'PENDING';
}
var surveyIdRegex = /surveys\/(SV_[a-zA-Z0-9]{15})/;
var canonicalId = (surveyIdRegex.exec(window.location.hash) || [])[1];
var fieldsetIdRegex = /fieldsets\/([\w-]+)/;
var fieldsetId = (fieldsetIdRegex.exec(window.location.hash) || [])[1];
var conjointIdRegex = /surveys\/SV_[a-zA-Z0-9]{15}\?conjointProjectId=(.+)/;
var conjointId = (conjointIdRegex.exec(window.location.hash) || [])[1];
var idpProjectRegex = /fieldsets\/[\w-]+\?(?:projectId|idpProjectId)=(IDP_.+|PROJ_.+)/;
var idpProjectId = (idpProjectRegex.exec(window.location.hash) || [])[1];
var resourceIdRegex = /surveys\/SV_[a-zA-Z0-9]{15}\?resourceId=(.+)/;
var resourceId = (resourceIdRegex.exec(window.location.hash) || [])[1];
var projectIdRegex = /surveys\/SV_[a-zA-Z0-9]{15}\?projectId=(.+)/;
var projectId = (projectIdRegex.exec(window.location.hash) || [])[1];
var url;
if (canonicalId) {
url = '/responses/surveys/' + canonicalId;
} else if (fieldsetId) {
url = '/responses/fieldsets/' + fieldsetId;
} else {
return rejectError(new Error('Missing surveyId for fast definition'));
}
if (conjointId) {
url += '?optProjectId=' + conjointId;
} else if (idpProjectId) {
url += '?idpProjectId=' + idpProjectId;
} else if (resourceId) {
url += '?resourceId=' + resourceId;
} else if (projectId) {
url += '?projectId=' + projectId;
}
window.fastDefinitionUrl = url;
var request = new XMLHttpRequest();
return attemptRequest();
})(window);
</script>
<link rel="icon" href="/brand-management/favicon">
<link rel="apple-touch-icon-precomposed" href="/brand-management/apple-touch-icon">
<link href="/responses/static/vendor/vendor.min.a113b2563.css" rel="stylesheet" type="text/css">
<link href="/responses/static/css/responsesclient.min.a49de54f5.css" rel="stylesheet" type="text/css">
</head>
<body ng-click="checkMenu()" ng-controller="MainController" keep-alive style="margin:0px;">
<div class="dp-container">
<div ng-view></div>
<div q-footer user-id="userId" language="userLanguage"></div>
</div>
</body>
<script src="/responses/static/vendor/vendor.min.a4f381856.js"></script>
<script src="/responses/static/js/responsesclient.min.ad8d40058.js"></script>
<script src="/wrapper/static/client.js"></script>
<script type="text/javascript" src="/project-workflow/static/bundle.js"></script>
<script type="text/javascript" src="https://static-assets.qualtrics.com/static/expert-review-ui/prod/response-iq.js"></script>
<script>
window.Qualtrics = {"User":{"brandId":"mindshare";
function hackAFixForProjectFramework() {
var surveyIdRegex = /surveys\/(SV_[a-zA-Z0-9]{15})/;
var fieldsetIdRegex = /fieldsets\/([\w-]+)/;
var canonicalId = (surveyIdRegex.exec(window.location.hash) || [])[1];
var fieldsetId = (fieldsetIdRegex.exec(window.location.hash) || [])[1];
window.Qualtrics.surveyId = canonicalId || fieldsetId;
}
// Hack a fix for updating to jquery 3.5 breaking project framework as they assumed it was ready sooner with jquery 3.5. Couldn't discover why, but it's somewhere in their code base.
hackAFixForProjectFramework();
var user = _.get(window, 'Qualtrics.User', {}),
requiredUserKeys = [
'userId',
'brandId',
'brandName',
'brandType',
'language',
'email',
'userName',
'firstName',
'lastName',
'accountType',
'accountCreationDate'
];
angular.module('responses-client').config([
'rsw.userServiceProvider',
function(userServiceProvider) {
try {
userServiceProvider.setUser(_.pick(user, requiredUserKeys));
} catch (e) {
console.log(e);
}
}
]);
</script>
</html>
I suspect the problem may be that the website is using a lot of javascript to dynamically change the responses. Above the HTML element I showed above, there are a bunch of "<'script type...'>" and src programs that I don't really understand, though I can guess from the names that they are handling the display of responses. Thinking it might be a loading problem, I've also tried making the program wait before searching for the element, but that didn't work either.
Cheers!
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 want to create a reporting tool based on export from google gmail api.
so the main thing i want to do is to retrieve , get all inbox messages by labels from my account in gmail, and display it in custom structure in my custom ehtml document.
i want to do it with php or javascript.
I have made some researches in Google API, but couldn't understand how to start working, from where?
i think it would be nice if could get the JSON data from this urls
Labels
Messages
how can i do it with javascript, what js libs i need to include, how to work with google Api? I have never worked with it before, so can anybody show me some simple full example?
Here is a full example showing how to load the Google APIs Javascript client, load the gmail API, and call the two API methods to list labels and inbox messages. There are a lot of javascript code snippets in the Gmai lAPI docs for each API call, so you can combine the structure of the code below with whatever specific code snippet to achieve what you want.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<div id="content"></div>
<p>Test gmail API.</p>
<script type="text/javascript">
// Enter a client ID for a web application from the Google Developer Console.
// In your Developer Console project, add a JavaScript origin that corresponds to the domain
// where you will be running the script.
var clientId = 'YOUR_CLIENT_ID_HERE';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = 'https://www.googleapis.com/auth/gmail.readonly';
// Use a button to handle authentication the first time.
function handleClientLoad() {
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('gmail', 'v1', function() {
listLabels();
listMessages();
});
}
/**
* Get all the Labels in the authenticated user's mailbox.
*/
function listLabels() {
var userId = "me";
var request = gapi.client.gmail.users.labels.list({
'userId': userId
});
request.execute(function(resp) {
var labels = resp.labels;
var output = ("<br>Query returned " + labels.length + " labels:<br>");
for(var i = 0; i < labels.length; i++) {
output += labels[i].name + "<br>";
}
document.getElementById("content").innerHTML += output;
});
}
/**
* Get all the message IDs in the authenticated user's inbox.
*/
function listMessages() {
var userId = "me";
var request = gapi.client.gmail.users.messages.list({
'userId': userId
});
request.execute(function(resp) {
var messages = resp.messages;
var output = "<br>Query returned " + messages.length + " messages:<br>";
for(var i = 0; i < messages.length; i++) {
output += messages[i].id + "<br>";
}
document.getElementById("content").innerHTML += output;
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</body>
</html>
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'm currently implementing a web smartphone application with Phonegap. On this application, users can post images they take with the phone camera on Facebook. This feature has been succesfully implemented only using javascript, by sending a base 64 encoded image. Now, I want to implement the same feature using Twitter.
I found some very interesting blog posts about this and I'm already be able to update the user status only using javascript... but I can't post images too using the update_with_media Twitter web service.
According too this post, someone says it's impossible to implement this operation without using a server side code (like a php script for example).
So my question is : is it possible to use the update_with_media Twitter web service only with javascript ?
I send you my code to have an overview of the current solution. I've taken this article as working base : http://oodlestechnologies.com/blogs/Twitter-integration-on-PhoneGap-using-ChildBrowser-and-OAuth-for-iOS-and-Android-Platforms
Here is my HTML code.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="../js/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../cordova-2.5.0.js"></script>
<script type="text/javascript" src="../js/childBrowser/childbrowser.js"></script>
<script type="text/javascript" src="../js/helpers/jsOAuth-1.3.6.js"></script>
<script type="text/javascript" src="../js/helpers/twitter.js"></script>
</head>
<body>
<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">
<td colspan="2"><textarea id="tweet"></textarea></td>
</tr>
<tr id="tweetBtn">
<td colspan="2" align="right">
<button id="tweeter" onclick="Twitter.tweet();">Tweet</button>
</td>
</tr>
<tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
</table>
<br/>
<br/>
<button onclick="javascript:location.reload();">Recharger la page</button>
</body>
</html>
Here is my twitter.js code : (The point is in the post method)
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
var root = this;
cb = window.plugins.childBrowser;
if (!localStorage.getItem(twitterKey)) {
$("#loginBtn").show();
$("#logoutBtn").hide();
$("tweetBtn").hide();
$("tweetText").hide();
}
else {
$("#loginBtn").hide();
$("#logoutBtn").show();
$("tweetBtn").show();
$("tweetText").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!");
}
// Consumer key : ...
// Consumer secret : ...
// GLOBAL VARS
var oauth; // It Holds the oAuth data request
var requestParams; // Specific param related to request
var options = {consumerKey: '...', consumerSecret: '...', callbackUrl: "http://www.google.fr"};
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: " + JSON.stringify(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.google.fr") >= 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() {
alert('Post !');
var theTweet = $("#tweet").val(); // You can change it with what else you likes.
oauth.post('https://upload.twitter.com/1/statuses/update_with_media.json',
{
'status': theTweet,
'media': //HERE IS THE PROBLEM, WHAT TO DO HERE ?
}, "multipart/form-data",
function(data)
{
alert('Data 1 !');
console.log('------Data1 : ' + data);
var entry = JSON.parse(data.text);
console.log(entry);
done();
},
function(data) {
//var json_result = JSON.parse(data);
//alert(json_result.text.error);
var entry = JSON.stringify(data);
console.log('------Data2 : ' + entry);
}
);
}
}
function done() {
alert("OKKK !");
$("#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();
}
After many tests (sending a base64 image, sending a blob, sending a binary file, ...) here is the return message from Twitter I have :
{\"errors\":[{\"message\":\"Internal
error\",\"code\":131}]}","xml":"","requestHeaders":{"Content-Type":"multipart/form-data"},"responseHeaders":{"date":"Fri,
19 Apr 2013 15:45:28
GMT","content-encoding":"deflate","strict-transport-security":"max-age=631138519","status":"500
Internal Server
Error","server":"tfe","content-type":"application/json;
charset=utf-8","version":"HTTP/1.1"}}
A "solution" (by send a blob) have been posted on the Twitter dev forum but not working for me : dev.twitter.com/discussions/6969
Does anyone want to implement the same feature or have a solution ? Thank you !
------ EDITED :
I just want to use Javascript and I don't want to implement any server-side solution (no PHP, C#, Java...).
According to the docs, Twitter requires the multipart/form-data enctype, which means a base64 string isn't going to work.
Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter ~ https://dev.twitter.com/docs/api/1/post/statuses/update_with_media
However, you could host an endpoint that takes base64, converts it to a real file, and forwards the request to Twitter. For example (untested):
<?php
$base64 = $_POST['image'];
$data = base64_decode( $base64 );
// Make name unique to avoid conflicts.
$temp_file = uniqid() . $_POST['name'];
// Save the file to a temp location.
file_put_contents( $temp_file, $data );
$temp_info = pathinfo( $temp_file );
$temp_type = $temp_info['extension'];
$temp_name = basename( $temp_file, '.' . $temp_type );
// OAuth library recommended by Twitter: https://github.com/themattharris/tmhOAuth
// See original: https://github.com/themattharris/tmhOAuth-examples/blob/master/images.php
require 'tmhOAuth.php';
require 'tmhUtilities.php';
$tmhOAuth = new tmhOAuth( array(
'consumer_key' => $_POST['consumer_key'],
'consumer_secret' => $_POST['consumer_secret'],
'user_token' => $_POST['user_token'],
'user_secret' => $_POST['user_secret'],
));
// note the type and filename are set here as well
// Edit: Not sure if the `type` and `filename` params are necessary.
$params = array( 'media[]' => "#{$temp_file};type={$temp_type};filename={$temp_name}" );
$code = $tmhOAuth->request( 'POST', $tmhOAuth->url( '1/status/update_with_media' ),
$params,
true, // use auth
true // multipart
);
// Remove temp file.
unlink( $temp_file );
if ( $code == 200 ) {
tmhUtilities::pr( json_decode( $tmhOAuth->response['response'] ) );
}
tmhUtilities::pr( htmlentities( $tmhOAuth->response['response'] ) );
?>
And you might call it like:
$.ajax({
// You'll want to use https to protect the oauth info.
url: "https://mysite.com/proxy.php",
type: "POST",
data: {
image: "base64 data...",
name: "foo.png",
consumer_key: options.consumerKey,
consumer_secret: options.consumerSecret,
user_token: options.accessTokenKey,
user_secret: options.accessTokenSecret
},
success: function( data ) {
console.log( data );
}
});
For anyone trying to post images to Twitter using client JS, I was able to post to twitter using the solution by gary-buynary-co-za (https://github.com/bytespider/jsOAuth/pull/11) at the end of this forum. Pretty much ended up using Phonegap FileTransfer and FileTransferOptions objects for transferring image to twitter api, but used jsOAuth for preparing FileTransferOptions headers and signatures. The solution could definitely be cleaned up though.