Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Google Drive API & Javascript

Greetings,

The Setup: 

  • HTML page developed in Google Cloud Workstation
  • To view the HTML page before pushing logic into production I use the below link

https://80-someAlphaNumericString-someAlphaNumericString-dev-main.cluster-99someAlphaNumericString.cloudworkstations.dev/?folder=/home/user/my_workspace

The Objective: connect to google Share Drive from HTML page and place a message within the specified DIV tags ( see above )

The HTML setup:

 

<td class="col2" valign="top">
<h3>Most Popular</h3>
<div id="most-popular" style="width: 100%; height: 150px; background-color: #e9e9e9; display: flex; justify-content: center; align-items: center;">
<!-- Connection status will be displayed here -->
</div>
</td>

 

 

The Javacript Setup:

 

<!-- JavaScript to connect to Google Drive -->
<script>
    const SHARED_DRIVE_ID = 'MY_SHARED_GOOGLE_DRIVE_ID';  // Replace with your actual Shared Drive ID


    function handleClientLoad() {
        gapi.load('client:auth2', initClient);
    }


    function initClient() {
        gapi.client.init({
            apiKey: 'MY_API_KEY',
            clientId: 'MY_CLIENT_ID',
            discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
            scope: 'https://www.googleapis.com/auth/drive.readonly'
        }).then(function () {
            return gapi.auth2.getAuthInstance().signIn();
        }).then(listFiles)
        .catch(function (error) {
            document.getElementById('most-popular').innerText = 'Sorry! Connection unsuccessful.';
            console.error('Error:', error);
        });
    }


    function listFiles() {
        gapi.client.drive.files.list({
            'pageSize': 10,
            'fields': 'nextPageToken, files(id, name)',
            'driveId': SHARED_DRIVE_ID,
            'corpora': 'drive',
            'includeItemsFromAllDrives': true,
            'supportsAllDrives': true
        }).then(function(response) {
            var files = response.result.files;
            if (files && files.length > 0) {
                document.getElementById('most-popular').innerText = 'Eureka! Successful connection.';
            } else {
                document.getElementById('most-popular').innerText = 'Eureka! Successful connection, but no files found.';
            }
        }).catch(function (error) {
            document.getElementById('most-popular').innerText = 'Sorry! Connection unsuccessful.';
            console.error('Error:', error);
        });
    }

</script>
<script async defer src="https://apis.google.com/js/api.js" onload="handleClientLoad()"></script>

 

 

Google Cloud Consolde: Google Drive API is enabled

Question 1: how do I setup the Google Drive API
Question 2: is the javascript problematic

Thanks in advance.

1 0 1,511
0 REPLIES 0
Top Labels in this Space