2nd question I've posted. still very new to web programming so excuse my ignorance.
I have a web based javascript which accesses a users Gmail account and downloads attachments to the local downloads folder as assigned in Chrome.
These files are then manually transferred to another directory and an Excel VBA script processes the files.
I'd like to be able to skip the manual transfer step and save the files directly to to the folder that Excel is looking at. I can get the Excel script to move the files but it only works if the user has not changed the Chrome default downloads folder location so it's not foolproof.
I believe this is impossible with javascript but is it possible with other languages or do I need a completely different approach? if it is possible with other languages which one and which methods do I need to be looking at?
This is the download section of the code as it stands at the minute at the request of a user OmegaStripes below:
<html>
<head>Google Drive File Download Process:
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<script type="text/javascript">
var CLIENT_ID = 'XXXXXXXXXXX';//removed for privacy
var SCOPES = 'https://www.googleapis.com/auth/drive';
/**
* Called when the client library is loaded to start the auth flow.
*/
function handleClientLoad() {
window.setTimeout(checkAuth, 1);
}
/**
* Check if the current user has authorized the application.
*/
function checkAuth() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': true
},
handleAuthResult);
}
/**
* Called when authorization server replies.
*
*/
function handleAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
var filePicker = document.getElementById('filePicker');
authButton.style.display = 'none';
filePicker.style.display = 'none';
if (authResult && !authResult.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
filePicker.style.display = 'block';
filePicker.onclick = downloadFile; // to allow for manual start of downloads
window.setTimeout(downloadFile(), 5000);
} else {
// No access token could be retrieved, show the button to start the authorization flow.
authButton.style.display = 'block';
authButton.onclick = function() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': false
},
handleAuthResult);
};
}
}
/**
* Start the file download.
*
*
*/
function downloadFile() {
console.log("call drive api");
gapi.client.load('drive', 'v2', makeRequest);
}
function makeRequest() {
console.log("make request");
var request = gapi.client.drive.files.list();
request.execute(function(resp) {
var x = []; //array for revised list of files to only include those not in the trash and those which have a suffix #FHM#
for (i = 0; i < resp.items.length; i++) {
if (resp.items[i].labels.trashed != true && resp.items[i].title.substring(0, 5) == "#FHM#") {
x.push([resp.items[i].title, resp.items[i].webContentLink, resp.items[i].id]);
}
}
if (x.length == 0) {
document.getElementById("filePicker").value = "There are no files to download";
}
for (i = 0; i < x.length; i++) {
console.log(x.length);
var dlUrl = x[i][1];
fileIdentity = x[i][2];
downloadUrl(dlUrl);
trashFile(fileIdentity);
filePicker.style.display = 'none';
document.getElementById("bodyText").innerHTML = "<br>Download " + (i + 1) + " of " + x.length + " completed.";
}
});
//window.setTimeout(function() {
// self.close;
//}, 5000);
}
function downloadUrl(url) {
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function trashFile(id) {
var requestTrash = gapi.client.drive.files.trash({
'fileId': id
});
requestTrash.execute(function(resp) {});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<!--Add buttons for the user to start the process -->
<input type="button" id="filePicker" style="display: none" value="If download does not start after 5 seconds, click here" />
<input type="button" id="authorizeButton" style="display: none" value="Authorize" />
<b id="bodyText"></b>
</body>
thanks
Your code could try to copy the files and if unsuccessful, ask the user to provide the correct path to the extracted file(s). You are right it cannot be done by Javascript. If you want to avoid having to ask the user for the path, you can implement a module to search for the file.
Is there a way you could know whether a file was extracted? If so, you can use this knowledge to know whether the lack of successful copying should trigger a file search or file path requesting.
Related
I have integrated authorize.net accept.js embedded iFrame in my application. Having trouble setting the transaction respone in my lambda function to get the response. I've seen similar questions on stack overflow but nothing worked out for me yet.
Using Nodejs for my backend and angular7 for the front-end.
I successfully get the token from my lambda function so my iframe appears on the ui. I've set \"showReceipt\": false providing url for cancel & continue, since the documentation says I have to set the show receipt parameter "false" in order to communicate with the IFrameCommunicator.html in the ui. But when I click on "Pay" its stuck at "Processing.." for a long time.
Following are the request & response headers respectively from the network tab:
* Cookie: __cfruid=deb63d2f12d9690aeea838cf7f31ada6da92bc1c-1602260930
* Host: test.authorize.net
* Origin: https://test.authorize.net
* Referer: https://test.authorize.net/payment/payment
* Sec-Fetch-Dest: empty
* Sec-Fetch-Mode: cors
*
Sec-Fetch-Site: same-origin
{"resultCode":"Ok","messageCode":"Ok","transactionData":{"accountType":"Discover","accountNumber":"XXXX0012","transId":"40055282319","responseCode":"4","authorization":"TYIUU7","merchantName":"iMart Inc.","totalAmount":"1999.9","dateTime":"10/09/2020 4:20:27 PM"}}
I'm sure the transaction is happening looking at the response but not sure why it's not connecting with the communicator.
I've read the steps in the documentation and also followed the GitHub sample code-https://github.com/AuthorizeNet/accept-sample-app, which made me more confused since they both say different things at some places. Following are the steps I've accomplished until now :
Created a lambda hosted payment function with all the settings (followed the correct sequence) to get back a token.
Created a hosted payment form to display the iframe.
Able to make a payment --> get the receipt page --> routing to success screen.
What I'm trying to accomplish:
After I make the payment, initial idea was to trigger a different lambda function based on the response from authorize.net without communicating with IFrameCommunicator.html, but as I cannot do that, I want to get a response to initiate the next process at the backend.
Also, we're not storing any user details in our server and not interested in creating a customer profile unless it's a necessary step to get the transaction response. Please suggest the step integration if I can do it in the same lambda function I've created to get a token or I would have to create a different one for this and when will that step be implemented?
I know about the Webhooks but not sure if it's an absolute necessity at this point of time when I'm just trying to implement a simple transaction.
I'm a newbie and I couldn't find a lot of examples related to the same to resolve my issues/confusions. Would highly appreciate if I get a clear explanation on the steps here and where am I going wrong.
Following is the code -
accept-hosted.js Lambda function:
merchantAuthenticationType.setName('*****');
merchantAuthenticationType.setTransactionKey('******');
var transactionRequestType = new ApiContracts.TransactionRequestType();
transactionRequestType.setTransactionType(ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION);
transactionRequestType.setAmount(Total);
var setting1 = new ApiContracts.SettingType();
var setting2 = new ApiContracts.SettingType();
var setting4 = new ApiContracts.SettingType();
var setting5 = new ApiContracts.SettingType();
var setting6 = new ApiContracts.SettingType();
var setting7 = new ApiContracts.SettingType();
var setting8 = new ApiContracts.SettingType();
var setting9 = new ApiContracts.SettingType();
var setting10 = new ApiContracts.SettingType();
var setting11 = new ApiContracts.SettingType();
setting2.setSettingName("hostedPaymentButtonOptions");
setting2.setSettingValue("{\"text\": \"Pay\"}");
setting1.setSettingName("hostedPaymentReturnOptions");
setting1.setSettingValue(
"{\"showReceipt\": false, \"url\": \"https://iMart.com/success.html\", \"urlText\": \"Continue\", \"cancelUrl\": \"https://iMart.com/error.html\", \"cancelUrlText\": \"Cancel\"}");
setting10.setSettingName("hostedPaymentOrderOptions");
setting10.setSettingValue("{\"show\": false, \"merchantName\": \"iMart Inc.\"}");
setting5.setSettingName("hostedPaymentPaymentOptions");
setting5.setSettingValue("{\"cardCodeRequired\": true, \"showCreditCard\": true, \"showBankAccount\": false}");
setting7.setSettingName("hostedPaymentShippingAddressOptions");
setting7.setSettingValue("{\"show\": false, \"required\": false}");
setting8.setSettingName("hostedPaymentBillingAddressOptions");
setting8.setSettingValue("{\"show\": false, \"required\": false}");
setting6.setSettingName("hostedPaymentSecurityOptions");
setting6.setSettingValue("{\"captcha\": true}");
setting4.setSettingName("hostedPaymentStyleOptions");
setting4.setSettingValue("{\"bgColor\": \"blue\"}");
setting9.setSettingName("hostedPaymentCustomerOptions");
setting9.setSettingValue("{\"showEmail\": false, \"requiredEmail\": false, \"addPaymentProfile\": true }");
setting11.setSettingName("hostedPaymentIFrameCommunicatorUrl");
setting11.setSettingValue("{\"url\": \"https://iMart.com/IFrameCommunicator.html\"}");
var settingList = [];
settingList.push(setting2);
settingList.push(setting10);
settingList.push(setting5);
settingList.push(setting7);
settingList.push(setting8);
settingList.push(setting6);
settingList.push(setting4);
settingList.push(setting9);
settingList.push(setting11);
settingList.push(setting1);
var alist = new ApiContracts.ArrayOfSetting();
alist.setSetting(settingList);
var firstname = new ApiContracts.UserField();
firstname.setName('First Name');
firstname.setValue(firstName);
var lastname = new ApiContracts.UserField();
lastname.setName('Last Name');
lastname.setValue(lastName);
var userFieldList = [];
userFieldList.push(firstname);
userFieldList.push(lastname);
var userFields = new ApiContracts.TransactionRequestType.UserFields();
userFields.setUserField(userFieldList);
var transactionSetting1 = new ApiContracts.SettingType();
transactionSetting1.setSettingName('duplicateWindow');
transactionSetting1.setSettingValue('120');
var transactionSetting2 = new ApiContracts.SettingType();
transactionSetting2.setSettingName('recurringBilling');
transactionSetting2.setSettingValue('false');
var transactionSetting3 = new ApiContracts.SettingType();
transactionSetting3.setSettingName('emailCustomer');
transactionSetting3.setSettingValue('true');
var transactionSetting4 = new ApiContracts.SettingType();
transactionSetting4.setSettingName('headerEmailReceipt');
transactionSetting3.setSettingValue('You are all set!');
var transactionSetting5 = new ApiContracts.SettingType();
transactionSetting5.setSettingName('footerEmailReceipt');
transactionSetting5.setSettingValue('This is the footer');
var getRequest = new ApiContracts.GetHostedPaymentPageRequest();
getRequest.setMerchantAuthentication(merchantAuthenticationType);
getRequest.setTransactionRequest(transactionRequestType);
getRequest.setHostedPaymentSettings(alist);
var ctrl = new ApiControllers.GetHostedPaymentPageController(getRequest.getJSON());
const basicAuth = encode.encode("*****", 'base64');
await axios({
method: 'post',
url: 'https://apitest.authorize.net/xml/v1/request.api',
headers: {
'Authorization': 'Basic '+basicAuth,
'Content-Type': 'application/json'
},
data:JSON.stringify(ctrl._request)
}).then(async (data : any)=>{
if(data.data.token) {
callback(null, data.data) ;
} else callErr(data);
});
async function callErr(data: any){
callback(null, res) ;
}
}
IFrameCommunicator.html:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Iframe Communicator</title>
<script type="text/javascript">
//<![CDATA[
function callParentFunction(str) {
if (str && str.length > 0
&& window.parent
&& window.parent.parent
&& window.parent.parent.AuthorizeNetPopup
&& window.parent.parent.AuthorizeNetPopup.onReceiveCommunication)
{
// Errors indicate a mismatch in domain between the page containing the iframe and this page.
window.parent.parent.AuthorizeNetPopup.onReceiveCommunication(str);
}
}
function receiveMessage(event) {
if (event && event.data) {
callParentFunction(event.data);
}
}
if (window.addEventListener) {
console.log('addEventListener');
console.log(receiveMessage);
window.addEventListener("message", receiveMessage, false);
} else if (window.attachEvent) {
window.attachEvent("onmessage", receiveMessage);
}
if (window.location.hash && window.location.hash.length > 1) { callParentFunction(window.location.hash.substring(1));
}
//]]/>
</script>
</head>
<body>
</body>
</html>
Angular code for showing the iFrame:
<iframe id="add_payment" class="embed-responsive-item panel" name="add_payment" width="100%" frameborder="0" scrolling="yes">
</iframe>
</div>
<form id="send_token" action="" method="post" target="add_payment" >
<input id="token" type="hidden" name="token" />
</form>
I have been struggling a lot since many days now with a time crunch. Would be really helpful if someone provides me with a good insight here. Please let me know if additional info is required. Thank you in advance!!!
Here are the answer for all your question, I hope it works :
1)if you are using iFrame then iFrameCommunicator is mandatory
2)the success url can only be used when you set "showReceipt" as true, here you cannot navigate automatically to yoour success page, this is the link for "Continue" button which appears when "showReceipt" is allowed
3)If you want to trigger any function or want to navigate after the response then add the following code in your html file
<script type="text/javascript">
$(document).ready(function () {
window.CommunicationHandler = {};
function parseQueryString(str) {
var vars = [];
var arr = str.split('&');
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
vars[pair[0]] = unescape(pair[1]);
}
return vars;
}
window.CommunicationHandler.onReceiveCommunication = function (argument) {
console.log('communication handler enter', argument);
var params = parseQueryString(argument.qstr)
switch (params['action']) {
case "resizeWindow":
console.log('resize'); break;
case "successfulSave":
console.log('save'); break;
case "cancel":
console.log('cancel'); break;
case "transactResponse":
sessionStorage.removeItem("HPTokenTime");
console.log('transaction complete');
var transResponse = JSON.parse(params['response']);
console.log('transaction complete1', transResponse);
// window.location.href = '/checkout/complete';
}
}
//send the token
$('#send_hptoken').submit();
});
</script>
i am new with google classroom api and i want to create a course on local machine. can i do it or not ?
if create then how using javascript ?
as i try ,got an error with code =>403, status="PERMISSION_DENIED" and message=> "Request had insufficient authentication scopes."
in my code i use function createCourse() to create a new course.
my code is below given
<!DOCTYPE html>
<html>
<body>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '782126680600-9kkg23inbnn9sv8ficcvjci2rgrnd648.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/classroom/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/classroom.courses.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
createCourse();
listCourses();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the names of the first 10 courses the user has access to. If
* no courses are found an appropriate message is printed.
*/
function listCourses() {
gapi.client.classroom.courses.list({
pageSize: 10
}).then(function(response) {
console.info(response.result);
var courses = response.result.courses;
appendPre('Courses:');
if (courses.length > 0) {
for (i = 0; i < courses.length; i++) {
var course = courses[i];
appendPre(course.name)
}
} else {
appendPre('No courses found.');
}
});
}
function createCourse(){
var newCourse = {'name': '9th Math','ownerId' : 'me','courseState' : 'PROVISIONED'};
gapi.client.classroom.courses.create(newCourse).then(function(response) {
console.info(response);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
please reply me..........
You have to update your scope from https://www.googleapis.com/auth/classroom.courses.readonly to https://www.googleapis.com/auth/classroom.courses.
According to the document, courses.create requires the following OAuth scope:https://www.googleapis.com/auth/classroom.courses to work.
The scope https://www.googleapis.com/auth/classroom.courses.readonly is used for listing and getting data. If there is a need to create, update you have to use https://www.googleapis.com/auth/classroom.courses to gain full access to the API.
Hope this helps.
I have this code where I can get the event from my calendar.
<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>
<button id="insert-button" style="visibility: hidden">Insert</button>
<script type="text/javascript">
// Enter a client ID for a web application from the Google Developer Console.
// The provided clientId will only work if the sample is run directly from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// In your Developer Console project, add a JavaScript origin that corresponds to the domain
// where you will be running the script.
var clientId = '823958590548-s5b4d4ngoj6tj2misdvrcdm3rt27jolr.apps.googleusercontent.com';
// Enter the API key from the Google Developer Console - to handle any unauthenticated
// requests in the code.
// The provided key works for this sample only when run from
// https://google-api-javascript-client.googlecode.com/hg/samples/authSample.html
// To use in your own application, replace this API key with your own.
var apiKey = 'AIzaSyDTqOkVPgBv5kCIqp5NXp7UwE0MKTjLmrU';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = 'https://www.googleapis.com/auth/calendar';
// Use a button to handle authentication the first time.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
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');
var insertButton = document.getElementById('insert-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
insertButton.style.visibility = '';
insertButton.onclick = handleInsertClick;
} else {
authorizeButton.style.visibility = '';
insertButton.style.visibility = 'hidden';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function handleInsertClick(event) {
makeInsertApiCall();
}
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'ashishpandit2312#gmail.com'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
function makeInsertApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.insert({
"calendarId": "primary",
resource:{
"summary": "Meeting",
"location": "Somewhere",
"start": {
"dateTime": "2015-02-21T01:00:00.000-07:00"
},
"end": {
"dateTime": "2015-02-21T04:25:00.000-08:00"
}
}
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
console.dir(resp);
}
});
});
}
</script>
<script
src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<div id='content'>
<h1>Events</h1>
<ul id='events'></ul>
</div>
<p>Connecting to Google Calendar with the Javascript Library.</p>
</body>
</html>
I want to get the events from multiple Google Calendars. What changes should I make to make it work and access multiple calendars of different people?
If you want to access multiple calendars of different people, the best way is to create a service account (which will do all requests to API's on behalf of users). So, users are not prompted with consent screen for authentication for accessing their calendar. Here are the steps:
Create a service account and you as the admin for the domain.
Share all the calendars to this service account.
For the service account to access users data, follow this link for domain wide delegation.
Check this link for service account sample code in java.
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>
I'm working with Skydrive APIs, and I would like my user tobe able to open a view about a file where you can edit it (the same view as we can have about a file when you're on the skydrive web page).
There may be a WL function for it but I can't find it. An other solution would be for me to get the URL of the view page and open it in a new window with javascript.
I have implemented this solution using SkyDrive and its API. You can try this script out within Microsoft's Interactive Live SDK online tool as well. The key is to obtain SkyDrive's redirect link for the file you are looking to open. This redirect link is returned for each file in the Get api's json result.
Processing Steps:
Initializes Windows Live jscript api client
Authenticate with Windows Live (skydrive) OAuth
GetFiles: Get a list of all files within your SkyDrive account. This could be adjusted for your needs and focused to just get a list for a specific folder with your SkyDrive account
onFilesComplete: iterate through json response looking for an item with a type='file' and file name you are looking to open. In this, case a file name 'robots.txt'
display details about the found file
using the found file's "link" attribute, open url in a new window browser window. This will open the file using SkyDrive default action. For known file types such as code files, this will open them in SkyDrive's online file editor. Otherwise, the default action will be to download the found file
Example Code:
WL.init({ client_id: clientId, redirect_uri: redirectUri });
WL.login({ "scope": "wl.skydrive" }).then(
function(response) {
getFiles();
},
function(response) {
log("Could not connect, status = " + response.status);
}
);
function getFiles() {
var files_path = "/me/skydrive/files";
WL.api({ path: files_path, method: "GET" }).then(
onGetFilesComplete,
function(response) {
log("Cannot get files and folders: " +
JSON.stringify(response.error).replace(/,/g, ",\n"));
}
);
}
function onGetFilesComplete(response) {
var items = response.data;
var foundFolder = 0;
for (var i = 0; i < items.length; i++) {
if (items[i].type === "file" &&
items[i].name === "robots.txt") {
log("Found a file with the following information: " +
JSON.stringify(items[i]).replace(/,/g, ",\n"));
foundFolder = 1;
//open file in a new browser window
window.open(items[i].link);
break;
}
}
if (foundFolder == 0) {
log("Unable to find any file(s)");
}
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}