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>
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 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>
I add the external script in head
http://www.google.com/jsapi
Body Part:
google.load("gdata", "1.s");
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;
}
after page open it goes to https://accounts.google.com/AuthSubRequestJS?session=1&scope=https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds&next=http%3A%2F%2Fmaharashtratimes.indiatimes.com%2Fsocial_gmail.cms
and it;shown The page you requested is invalid. Please help.................
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