Google Drive API javascript
Asked Answered
M

3

16

I'm trying to use the Google drive to list files.

Using the answer in https://stackoverflow.com/a/11280257 I found a problem that I can't discover the reason.

var clientId = '*********.apps.googleusercontent.com';
var apiKey = '##########';
var scopes = 'https://www.googleapis.com/auth/drive';


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');

    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;
}

function makeApiCall() {  
    gapi.client.load('drive', 'v2', makeRequest);   
}

function makeRequest()
{
    var request = gapi.client.drive.files.list({'maxResults': 5 });

    request.execute(function(resp) {          
        for (i=0; i<resp.items.length; i++) {
            var titulo = resp.items[i].title;
            var fechaUpd = resp.items[i].modifiedDate;
            var userUpd = resp.items[i].lastModifyingUserName;
            var userEmbed = resp.items[i].embedLink;
            var userAltLink = resp.items[i].alternateLink;

            var fileInfo = document.createElement('li');
            fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd ));                
            document.getElementById('content').appendChild(fileInfo);
        }
    });    
}

I have this error:

Uncaught TypeError: Cannot read property 'files' of undefined 

in the line

var request = gapi.client.drive.files.list({'maxResults': 5 });
Mamoun answered 3/7, 2012 at 17:19 Comment(0)
M
24

Using

var request = gapi.client.request({
        'path': '/drive/v2/files',
        'method': 'GET',
        'params': {'maxResults': '1'}
        });

instead of

var request = gapi.client.drive.files.list({'maxResults': 5 });

resolved the problem!

Mamoun answered 4/7, 2012 at 10:50 Comment(2)
Thanks for sharing! This works for me to. I do find it odd that code that was posted as an example in the API documentation does not work as expected ...Vogt
2023 and I'm trying to use the Google Drive API 'JavaScript quickstart' which has multiple issues including one fixed by this answer. Thank you. The other issue is with the quickstart is that you have to omit the 'apiKey: API_KEY,' when calling 'gapi.client.init' to get it working.Hot
B
7

Code looks OK and you're correctly waiting until gapi.client.load completes. Might just be an error with loading the Drive JS files or some other issue (maybe bad JS file cached?). I modified your example a little bit to run on jsfiddle, take a look at http://jsfiddle.net/Rbg44/4/ for the full example:

HTML:

<button id="authorize-button">Authorize</button>
<div id="content">Files:</div>

JS:

var CLIENT_ID = '...';
var API_KEY = '...';
var SCOPES = '...';

function handleClientLoad() {
    gapi.client.setApiKey(API_KEY);
    window.setTimeout(checkAuth,1);
}

function checkAuth() {
    var options = {
        client_id: CLIENT_ID,
        scope: SCOPES,
        immediate: true
    };
    gapi.auth.authorize(options, 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) {
    var options = {
        client_id: CLIENT_ID,
        scope: SCOPES,
        immediate: false
    };
    gapi.auth.authorize(options, handleAuthResult);
    return false;
}

function makeApiCall() {  
    gapi.client.load('drive', 'v2', makeRequest);   
}

function makeRequest() {
    var request = gapi.client.drive.files.list({'maxResults': 5 });
    request.execute(function(resp) {          
        for (i=0; i<resp.items.length; i++) {
            var titulo = resp.items[i].title;
            var fechaUpd = resp.items[i].modifiedDate;
            var userUpd = resp.items[i].lastModifyingUserName;
            var userEmbed = resp.items[i].embedLink;
            var userAltLink = resp.items[i].alternateLink;

            var fileInfo = document.createElement('li');
            fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + 
                ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd ));                
            document.getElementById('content').appendChild(fileInfo);
        }
    });    
}

$(document).ready(function() {
  $('#authorize-button').on('click', handleAuthClick);
  $.getScript('//apis.google.com/js/api.js', function() {
    gapi.load('auth:client', handleClientLoad);
  });
});

Can you check in your browsers dev tools if there is any sort of issue in the request made when you call gapi.client.load()?

Berceuse answered 10/1, 2013 at 19:17 Comment(0)
S
4

You need to write this :

gapi.client.load('drive', 'v2', null);  
Sorce answered 3/4, 2014 at 9:15 Comment(2)
This is a helpful response. It makes the example code from Google work.Grantinaid
2023 now and I was hoping this would resolve my issue with the quickstart but doesn't seem to. Sandro's answer works.Hot

© 2022 - 2024 — McMap. All rights reserved.