Access the Google Picker API using pre-saved login credentials

Recently, I successfully integrated the Google Picker API into my project. This feature prompts a window for Google authentication and then displays all the files stored in Google Drive.

However, I now have a specific requirement where I want to access these files without triggering the authentication popup. Instead, I intend to use the username and password that are already stored in my database.

Is there a method through which I can pass the user credentials, receive authorization, and access the files accordingly?

Here is a snippet of my code:

<script>
  function onApiLoad() {
    gapi.load('auth', { 'callback': onAuthApiLoad });
    gapi.load('picker');
  }

function onAuthApiLoad() {
   window.gapi.auth.authorize({                         
   'client_id': 'xxxx.apps.googleusercontent.com',
   'scope': ['https://www.googleapis.com/auth/drive']
    }, handleAuthResult);
}

var oauthToken;
function handleAuthResult(authResult) {
   if (authResult && !authResult.error) {
      oauthToken = authResult.access_token;
      createPicker();
   }
}


function createPicker() {                    
   var picker = new google.picker.PickerBuilder()
                .addView(new google.picker.DocsUploadView())
                .addView(new google.picker.DocsView())                        
                .setOAuthToken(oauthToken)
                .setDeveloperKey('xxxx')                           
                .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
                .addView(new google.picker.VideoSearchView().setSite(google.picker.VideoSearchView.YOUTUBE))
                .setCallback(pickerCallback)
                .build();
                 picker.setVisible(true);
      }
</script>

Answer №1

When initializing the picker with createpicker(), make sure to include the access token to avoid consent screen prompts. Update your code by changing createpicker() to createPicker(oauthToken). Here is a sample code snippet for reference:

function createPicker(token) {
 if (pickerApiLoaded && token) {


 var picker = new google.picker.PickerBuilder()
       .addView(new google.picker.DocsView().setIncludeFolders(true)) //Display all files and folders            

     .setOAuthToken(token)//Access Token

     .setDeveloperKey(DEVELOPER_KEY)
     .setCallback(pickerCallback)
     // Set Picker dialog size
     .setSize(DIALOG_DIMENSIONS.width ,
         DIALOG_DIMENSIONS.height )
     .build();
 picker.setVisible(true);
} else {
 showError('Unable to load the file picker.');
}
}

Answer №2

Give this code a try with your access token included:

function startFilePicker(access_token) {
 if (access_token) {
  var filePicker = new google.picker.PickerBuilder()
            .addView(new google.picker.DocsUploadView())
            .addView(new google.picker.DocsView())                        
            .setOAuthToken(access_token)
            .setDeveloperKey('xxxx')                           
            .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
            .addView(new google.picker.VideoSearchView().setSite(google.picker.VideoSearchView.YOUTUBE))
            .setCallback(pickerCallback)
            .build();
             filePicker.setVisible(true);
} else {
 showError('Failed to initialize the file picker.');
}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the possibilities of integrating React with multiple Material UI dialogs

My goal is to have two dialog boxes, one for the sign-up page and another for the login page. When a user clicks on the sign-up button on the top page, the sign-up screen should appear. Likewise, when they click on the login button on the sign-up page, the ...

Using a curly brace in a React variable declaration

After completing a react tutorial, I started customizing the code to suit my requirements. One specific section of the code involved a component that received a parameter called label. render() { const { label } = this.props; ... } For instance, I re ...

Sending an array of functions to the onClick event of a button

Having difficulty with TypeScript/JavaScript Currently working with an array of functions like this private listeners: ((name: string) => void)[] = []; Successfully adding functions to the array within another function. Now looking to trigger those ...

Regular expression for identifying a specific attribute paired with its corresponding value in a JSON object

Below is a JSON structure that I am working with: 'use strict'; // some comment is going to be here module.exports = { property1: 'value1', property2: 999, }; I am looking to remove the property2: 999, from the JSON. I attempted ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Adjusting the starting point on a 2D canvas with EaselJS translation

When using plain javascript, I was able to change the origin of the canvas to the center by following these steps: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = 1024; canvas.heigh ...

Why does Cloudinary fail to delete the tmp folder it creates after finishing the upload process?

Recently, I've been working on implementing an upload Post feature for my app. The process involves submitting a file from the frontend, sending it to the backend, and then uploading it to Cloudinary's cloud servers. However, before the upload to ...

How can I arrange an ItemTemplate and Alternating ItemTemplate next to each other in a Gridview layout?

My webpage features a "Reports" page that will dynamically display buttons (formatted ASP:Hyperlinks) based on the number of active reports in a table. While everything works well, I am struggling with achieving the desired layout. I want my buttons to app ...

Choose the default text option for your AngularJS dropdown menu

I am facing an issue with my angularjs dropdownlist that is using ng-options. <select ng-options="perlocation.name for perlocation in locations" ng-model="locationDropdown"> Even though my dropdown list loads correctly, the selected option 0 is dis ...

Loading Ajax content on a webpage

Recently, I've been impressed with the layout of Google Play Store on a web browser. I am eager to replicate that same smooth browsing experience on my own website. Specifically, I want to create a feature where selecting a category or item doesn&ap ...

Utilizing ThemeProvider in a Different Component in React

In my App.js file, I have a function that toggles between light and dark mode themes: import { createTheme, ThemeProvider } from '@mui/material/styles' import Button from '@mui/material/Button' import Header from './components/Head ...

Access the input field value with PHP and store it in a variable

I previously looked into this issue, but the solution provided in the accepted answer did not resolve it for me: How to get input field value using PHP Below is an excerpt from my result.php file: ... <th> <form name="form" action= ...

Creating a JSON data array for Highcharts visualization: rearranging values for xAxis and columns

I am facing an issue with my column chart where JSON data is being parsed in the "normal" form: Years are displayed on the xAxis and values on the yAxis (check out the fiddle here): array( array( "name" => "Bangladesh", ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

Using the Google Picker API to dynamically load a file picker when needed

I am interested in integrating the Google Picker API. The provided example demonstrates the picker being loaded upon page load, but I would like the picker to load when a specific action is taken, such as clicking on a button. However, implementing this be ...

jQuery can add scrolling buttons to a webpage

I have been trying to create a list that can be scrolled through by using buttons, while also having a visible and functional scrollbar. However, I am struggling to edit my code in a way that allows both features to work simultaneously. It seems like I can ...

What is the best way to populate a remote html page in real-time according to user input?

Is it feasible to use only JavaScript and HTML to allow users to select from a list of options and then print a page that includes a checklist of their selections? ...

Verifying One Time Password (OTP) from MSG91 URL using ReactJS

Currently, I am working on a small project that involves receiving and verifying OTPs from MSG91. While I have managed to successfully receive OTPs using MSG91, I am encountering an issue when trying to verify OTPs - specifically, I keep getting an error ...

Is it possible to pass the index variable of a for loop to a different function?

As a current bootcamp student, I have a question about passing the index of a for loop to another function. Specifically, I am trying to fetch data from an API (which provides me with a random cryptocurrency from an array) 4 times and then pass that data ...

Error encountered: npm process ended unexpectedly with error code ELIFECYCLE and errno 2

Whenever I attempt to run - npm run dev in my command prompt, I encounter the following error: Insufficient number of arguments or no entry found. Alternatively, run 'webpack(-cli) --help' for usage info. Hash: af4cfdb00272137cb4d3 Version: web ...