embed google drive picker as a part of page - javascript

I want to embed/implement Google Drive as a part of my page; like a normal grid or a table instead of having as a popup. I have took a reference from GoogleAPI page. Also, researched many things for my requirements but nothing would worked for me.
Here is the javascript code that I am using
// The Browser API key obtained from the Google API Console.
// Replace with your own Browser API key, or your own key.
var developerKey = 'xxxxxxxxxxxxxx';
// The Client ID obtained from the Google API Console. Replace with your own Client ID.
var clientId = "xxxxxxxxxxxx.apps.googleusercontent.com"
// Replace with your own project number from console.developers.google.com.
// See "Project number" under "IAM & Admin" > "Settings"
var appId = "xxxxxxxxxxxx";
// Scope to use to access user's Drive items.
var scope = ['https://www.googleapis.com/auth/drive'];
var pickerApiLoaded = false;
var oauthToken;
var picker;
// Use the Google API Loader script to load the google.picker script.
function loadPicker() {
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 searching images.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.DocsView()
.setIncludeFolders(true)
.setOwnedByMe(true);
picker = new google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.setAppId(appId)
.setOAuthToken(oauthToken)
.addView(view)
.addView(new google.picker.DocsUploadView().setIncludeFolders(true))
.setDeveloperKey(developerKey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
alert('The user selected: ' + fileId);
}
}
<button onclick="loadPicker(); return false;">Pick From Google Drive</button>
<div id="result"></div>
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js"></script>

Use PickerBuilder.toUri() instead of PickerBuilder.build().
It will return picker url and set this to iframe.

According to the issue reported here,
gapi.auth is deprecated. You should use gapi.auth2 instead.
From Google Developers
Use,
gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com',
scope : scope ,
});
and it will return a Promise
gapi.auth2.GoogleAuth
A full reference can be seen in the Google Developer Page

It sounds like you want to use the Google Drive API rather than the picker API.
This allows you to query drive for files without using the GUI.
https://developers.google.com/drive/v3/web/quickstart/js
The example in this quickstart prints out a list of files from the authorized account onto the page.

Related

Google Drive API Picker acting weird

I'm working on a React application which need to access Google Drive API.
My basic settings are correct (api key, client id, application id, etc...)
I can open the oauth Dialog and sign in (I can get the Oauth token), then I run a function which open the picker.
Here's my problem :
I made a first version with a only HTML basic page and the picker was working great even if I had these errors (which seems to be recurrent)
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://docs.google.com') does not match the recipient window's origin ('myURL').
Invalid 'X-Frame-Options' header encountered when loading ...
POST https://docs.google.com/picker/logImpressions 400
But now in my React app, the picker is open and I can click on all Files BUT clicking on "Save", "Cancel" don't trigger anything. Same thing if I try to use filter options or if I try to close the picker.
Do you have any idea of what can cause this ?
My code :
React
<ButtonCustom onClick={()=>loadGoogleDrive(this.state.channel,this.onSuccess)}>Importer depuis Gdrive</ButtonCustom>
and the loadGoogleDrive function :
var developerKey = 'here goes my api key';
// The Client ID obtained from the Google API Console. Replace with your own Client ID.
var clientId = 'here goes my client id';
// Replace with your own project number from console.developers.google.com.
// See "Project number" under "IAM & Admin" > "Settings"
var appId = 'here goes my app id';
console.log(developerKey,clientId,appId)
// Scope to use to access user's Drive items.
var scope = ['https://www.googleapis.com/auth/drive.readonly'];
var pickerApiLoaded = false;
var oauthToken;
// Use the Google API Loader script to load the google.picker script.
function loadPicker() {
if(oauthToken){
gapi.load('picker', {'callback': onPickerApiLoad});
}
else{
gapi.load('auth', {'callback': onAuthApiLoad});
}
}
function onAuthApiLoad() {
gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
gapi.load('picker', {'callback': onPickerApiLoad});
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for searching images.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var view = new window.google.picker.View(window.google.picker.ViewId.DOCS);
view.setMimeTypes("image/png,image/jpeg,image/jpg,application/json,application/vnd.google-apps.document");
// MimeTypes a ajouter/modifier selon les besoins
var picker = new window.google.picker.PickerBuilder()
// .enableFeature(google.picker.Feature.NAV_HIDDEN) Permet de cacher le bouton UPLOAD
.enableFeature(window.google.picker.Feature.MULTISELECT_ENABLED)
.setAppId(appId)
.setOAuthToken(oauthToken)
.addView(view)
//.addView(new google.picker.DocsUploadView())
.setDeveloperKey(developerKey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
console.log('datas',data)
if(data.docs){
importCallback(data.docs,'googledrive',{'oauthToken' : oauthToken});
}
}
loadPicker();
}
Here's a picture from the bug, i can click on the pictures but not on anything else
Sorry for the blur effect I'm not allowed to share the pictures.
Thanks and if you need any more informations i'll be glad to help
(and sorry for my bad english)
UPDATE
It appears there were conflicts between plugins (we dont know which one because we are using a lot of them). One of my coworker fixed this by putting all the GDrive api code on a new independent popup.

Google Drive API Picker v3 (May 2018) window disappears and gives .split is not a function error

Using Google Drive API Picker v3, Chrome Version 66.0.3359.139
Each account can log into their account one time and one time only.
You can switch back and forth between accounts, but if you try to access the same account 2 times in a row... it will fail with the .split is not a function.
There seems to be an error when the oauthToken attempts to be parsed back on the client side.
Why is the auth not updating? Is there a setting or something I am missing?
Chrome stack trace:
3723580519-idpiframe.js:26 Uncaught TypeError: (b || "").split is not a function
at Xa (3723580519-idpiframe.js:26)
at 3723580519-idpiframe.js:61
at 3723580519-idpiframe.js:55
at eb.h.getItem (3723580519-idpiframe.js:35)
at Ib.Q.o (3723580519-idpiframe.js:55)
at Ib.o (3723580519-idpiframe.js:61)
at Sb (3723580519-idpiframe.js:68)
at W.h.kb (3723580519-idpiframe.js:76)
at Object.A (3723580519-idpiframe.js:83)
at Jb.Cb (3723580519-idpiframe.js:63)
Here is my code:
var clientId = 'stuff.apps.googleusercontent.com';
var scope = ['https://www.googleapis.com/auth/drive.readonly'];
var appId = "my-app-id";
var pickerApiLoaded = false;
function loadPicker() { //called when js api loads
gapi.load('auth2', { 'callback': onAuthApiLoad });
gapi.load('picker', { 'callback': onPickerApiLoad });
}
function onAuthApiLoad() {
var authBtn = document.getElementById('accessGoogleDrive');
authBtn.disabled = false;
authBtn.addEventListener('click', function () {
gapi.auth2.authorize({
client_id: clientId,
scope: scope,
//prompt: "consent"
'immediate':false
}, handleAuthResult);
});
}
function onPickerApiLoad() {
pickerApiLoaded = true;
}
function handleAuthResult(authResult) {
console.log("handleAuthResult", authResult);
if (authResult && !authResult.error) {
createPicker(authResult.access_token);
}
}
// Create and render a Picker object for searching images.
function createPicker(oauthToken) {
if (pickerApiLoaded && oauthToken) {
console.log("Creating Picker for Google Drive...");
var view = new google.picker.View(google.picker.ViewId.PDFS);
var picker = new google.picker.PickerBuilder()
.setAppId(appId)
.setOrigin("http://localhost:8080")
.setOAuthToken(oauthToken)
.addView(view)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
console.log("Successfully picked: ", data);
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
alert('The user selected: ' + fileId);
}
}
//Google APIs script: "https://apis.google.com/js/api.js?onload=loadPicker"
THANKS IN ADVANCE!
Change
var scope = ['https://www.googleapis.com/auth/drive.readonly'];
to
var scope = 'https://www.googleapis.com/auth/drive.readonly';
as per https://github.com/google/google-api-javascript-client/issues/13#issuecomment-290129284

Failing to export variable defined in function to another concurrently-ran JS file

I have been reading different posts on Google and SO, but I just can't figure out why this does not work.
There are 2 HTML and 2 JS files involved in this case (explanation given below in words after the code chunks).
1) index.html
<div id="center">
<img id="logo" src="../img/logowshadow.png" alt="logo">
<p id="para">Get your google slides!</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Sign in</button>
<button id="signout-button" style="display: none;">Sign Out</button>
</div>
<script src="../js/homePage.js"></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>
2) homePage.js
var apiKey = 'AIzaSyCSjg3rrx6Obl4ngZsDlFlV4degUJSMvbw';
var discoveryDocs = ["https://slides.googleapis.com/$discovery/rest?version=v1"];
var clientId = '408869653199-ruoft30vmoqrgpku3us3qd2leb3k6tp1.apps.googleusercontent.com';
var scopes = 'https://www.googleapis.com/auth/presentations.readonly https://www.googleapis.com/auth/drive';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
var user;
var authResponse;
var oauthToken;
var pickerApiLoaded = false;
var chosenPresentation = null;
function handleClientLoad() {
// Load the API client and auth2 library
gapi.load('client:auth2', initClient);
//Load the Picker API
gapi.load('picker', onPickerApiLoad);
}
function initClient() {
gapi.auth2.init({
apiKey: apiKey,
discoveryDocs: discoveryDocs,
clientId: clientId,
scope: scopes
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Set the current Google User
gapi.auth2.getAuthInstance().currentUser.listen(updateUser);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
// Callback to make sure that the Picker API has loaded
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
// Store the current Google user
function updateUser(gUser) {
user = gUser;
updateToken();
}
// Store the access token
function updateToken() {
authResponse = user.getAuthResponse(true);
oauthToken = authResponse.access_token;
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
createPicker();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
// Create and render a Picker object for picking user slides
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
addView(google.picker.ViewId.PRESENTATIONS).
setOAuthToken(oauthToken).
setDeveloperKey(apiKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// 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].replace('edit', 'present');
var item_name = doc[google.picker.Document.NAME];
alert('You picked ' + item_name);
//export the chosen presentation for use in mobileControl.js
chosenPresentation = doc[google.picker.Document.ID];
alert("chosen: " + chosenPresentation);
exports.chosenPresentation = chosenPresentation;
window.location.replace(url);
}
}
3) mobile.html
<div id="instructions">
<p>Swipe <b>left</b> to go to the previous slide.</p>
<p>Swipe <b>right</b> to go to the next slide.</p>
</div>
<script src="../js/mobileControl.js"></script>
and 4) mobileControl.js
alert("Loaded the JavaScript!"); //Shows up
var m = require('./homePage.js');
alert("imported"); //Does not show up
alert(m.chosenPresentation); //Does not show up
To put in words what my code is trying to achieve: users will be able to sign in to their google accounts, and select a set of Presentation found on their Google drive. I want to pass the Presentation ID on from homePage.js to mobileControl.js, and I attempted to do so using Node's exports. I suspect that it is not working because both scripts are run 'at the same time' (index.html is meant to run on the computer, while mobile.html runs on a mobile device...concurrently). But I am not sure if I am right in identifying the cause, and if so, is there a way to export the variable from within the function after it has been defined? Perhaps I should detect it when the slide has been selected, and only load mobilePage.js after everything in homePage.js has ran?
My apologies for the long read, but my previous attempt at diluting the example obviously failed miserably so...
Update: user #vsenko is totally right in saying that I have mixed up client-side programming and server-side programming, so do read up more on this if you are facing the same issue as me
As far as I can see, you are trying to load .js files with NodeJS specific API (RequireJS API to precise) directly on the web page. This is not going to work because browsers do not implement it natively. To utilize this API you will have to use a preprocessor (Webpack, Browserify or something else).
Other apparent problem with your approach is that you assume that it is possible to transfer data between different devices using something that look like NodeJS modules. But it is not possible, you will have transfer data over the network between your devices directly or though your server.

Google picker auth popup is being blocked

I have a mobile site which lists jobs, the user applies and uploads their CV (resume) - I want them to be able to choose a file from their Google Drive.
I've created the Hello world example here - https://developers.google.com/picker/docs/ (code reproduced here for convenience)
Problem is that if not already logged into Drive, a popup to login is launched. This is bad enough on a desktop but really bad on a phone.
I have tried this solution, but get 'TypeError: gapi.auth is undefined'
I also tried launching the picker from an onclick event rather than the onload as described by the docs.
function launchDrive()
{
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
<input type='button' value='Launch Drive' onclick='launchDrive();'>
Sample Google code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Picker Example</title>
<script type="text/javascript">
var developerKey = 'xxxxxxxYYYYYYYY-12345678';
var clientId = "1234567890-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com"
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
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().
addView(google.picker.ViewId.PHOTOS).
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 = 'You picked: ' + url;
document.getElementById('result').innerHTML = message;
}
</script>
</head>
<body>
<div id="result"></div>
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
13 May 2015 edit
Further to Jason's answer, here is what I also tried (called by a button oncllick):
function launchDrive()
{
//gapi.load('auth', {'callback': onAuthApiLoad});
gapi.auth.init(onAuthApiLoad);
gapi.load('picker', {'callback': onPickerApiLoad});
}
You will want to call gapi.auth.init. See the docs here: https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthinit
Initializes the authorization feature. Call this when the client loads to prevent popup blockers from blocking the auth window on gapi.auth.authorize calls.
To solve your issue you need to understand how google performs oauth in your case:
gapi performs init actions
gapi opens a google auth page in new popup window and you perform login in it
after login succeeded gapi gets notified and you receive your token
Why browser blocks the popup in 2nd step:
original event is not present anymore in window (window.event is destroyed).
User manually blocked the popup from current site
So if user didn't block a popup and you popup is still blocked, gapi actions look something like:
<input type="button" onclick="auth" value="click"/>
function auth() {
setTimeout(function() {
// by this time window.event is destroyed, that's why browser blocks the popup
window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');
}, 100)
}
So what you should do:
Make sure that after button click you don't perform any asynchronous actions like XHRequests or other
Make sure gapi is inited and ready by the time users click on the button, so by the time gapi needs to create a popup, window.event won't be null. So move all gapi init methods to DOMContentLoaded.
As another option you could use server-side oauth flow, which means instead of popup user will be redirected in current tab to gauth page.
I have it working now.
In the example for the picker, https://developers.google.com/picker/docs/, it calls:
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
In this example, https://developers.google.com/api-client-library/javascript/start/start-js, it calls:
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
Using client.js fixes the 'TypeError: gapi.auth is undefined' issue, and thus the login popup works.
Maybe api.js is an older version of the API?
Just Skip to the bottom
Here's the code that works for me currently. This is my first hour using this API though, so I really don't know what any of these functions do yet, nor do I know what the proper order and error handling is just yet, but at least this is functional now. Maybe it'll help someone else in the future.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Picker Example</title>
</head>
<body style="width: 70%; margin: 100px auto;">
<!-- Added a button to open picker -->
<button onclick="loadPicker();" >Open from GoogleDrive</button>
<div id="result"></div>
<!-- Moved to end of body tag instead of head -->
<script type="text/javascript">
// The Browser API key obtained from the Google API Console.
// Replace with your own Browser API key, or your own key.
var developerKey = '<IDK WHAT'S SUPPOSED TO GO HERE, BUT ITS OK>';
// The Client ID obtained from the Google API Console. Replace with your own Client ID.
var clientId = "<YOUR CLIENT ID GOES HERE>.apps.googleusercontent.com"
// Replace with your own project number from console.developers.google.com.
// See "Project number" under "IAM & Admin" > "Settings"
var appId = "<YOUR APP ID GOES HERE>";
// Scope to use to access user's Drive items.
var scope = ['https://www.googleapis.com/auth/drive'];
var pickerApiLoaded = false;
var oauthToken;
// Use the Google API Loader script to load the google.picker script.
function loadPicker() {
// This needs to be client:auth2 no client
gapi.load('client:auth2', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
// we need to init gapi.client with the clientId and scope first
gapi.client.init({
clientId: clientId,
scope: scope
});
// Now we can authorize? seems like the same thing here
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 searching images.
function createPicker() {
// Wow this is a mess
if (pickerApiLoaded && oauthToken) {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes("image/png,image/jpeg,image/jpg");
var picker = new google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.setAppId(appId)
.setOAuthToken(oauthToken)
.addView(view)
.addView(new google.picker.DocsUploadView())
// Guess this is... optional?
//.setDeveloperKey(developerKey)
.setCallback(pickerCallback)
.build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
alert('Selected fileId: ' + fileId);
}
}
</script>
<!-- The Google API Loader script. Removed the autorun -->
<script type="text/javascript" src="https://apis.google.com/js/api.js"></script>
</body>
</html>
Edit: If you get a pop-up window that doesn't load, just close it and click the button again. That fixed another issue I just had.
Again, I don't know what I'm doing yet, so hopefully I can get a better understanding of this and clarify things later.
E2: Ah, there's more information about OAuth2 over on the Javascript GAPI documentation page which can be found here: https://developers.google.com/api-client-library/javascript/features/authentication
From another document, it appear that gapi.load('client', callback) will load auth2 if not already loaded. Calling gapi.load('client:auth2', callback) will just save 1 network request.
Note: when you authorize your application using Oauth 2.0, you do not also need to set the API key as in the first example. However, it is a good practice to do so, in case your code ever expands to handle unauthorized requests.
That explains why I could remove the API/developer key.
Edit 3: Ok the above code is technically wrong.
Warning: do not use this method alongside the recommended gapi.auth2.init and signIn flow. These are two distinct behaviors (Authorization for gapi.auth2.authorize vs Authentication for gapi.auth2.init/signIn) and will have unexpected issues if used within the same application.
autorize is for single use authentications (if you were logged into 2 google accounts for instance). While using gapi.init() is meant to be for a more long term session (like for logging in and out of a website).
How this is working currently, I do not know.
Don't use the above code, just wanted to document the progress. Here's a better demo working with getAuthResponse()
<html>
<head></head>
<body>
<div style="padding: 50px">
<h2 style="color: #2196f3;">Status: <span id='status'></span></h2>
<button id="signin-button" onclick="handleSignInClick()">Sign In</button>
<button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
<button id="signout-button" onclick="openFile()">Open File</button>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var cid = '<CLIENTID_HERE>';
var scope = 'https://www.googleapis.com/auth/drive';
var authenticated = false;
var pickerLoaded = false;
var auth = null;
var user = null;
var response = null;
var token = null;
var stat = $('#status');
function openFile() {
gapi.load('client:auth2', initClient);
gapi.load('picker', onPickerLoad);
}
function initClient() {
stat.html("starting");
gapi.client.init({
clientId: cid,
scope: scope
}).then(
function () {
console.log("init");
// Check if we are logged in.
auth = gapi.auth2.getAuthInstance();
auth.isSignedIn.listen(onStatusChange);
authenticated = auth.isSignedIn.get();
stat.html(authenticated);
if (authenticated) {
stat.html("Logged In!");
user = auth.currentUser.get();
response = user.getAuthResponse(true);
token = response.access_token;
showPicker();
} else {
stat.html("Logged Out!");
}
}, function(){stat.html("error")});
}
function onStatusChange(isSignedIn) {
if (isSignedIn) {
stat.html("Logged In!");
authenticated = true;
user = auth.currentUser.get();
response = user.getAuthResponse(true);
token = response.access_token;
showPicker();
showPicker();
} else {
authenticated = false;
stat.html("Logged Out!");
}
}
function handleSignInClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
alert("signed out");
}
function onPickerLoad() {
pickerLoaded = true;
showPicker();
}
function showPicker() {
if (pickerLoaded && authenticated) {
var view = new google.picker.View(google.picker.ViewId.DOCS);
var picker = new google.picker.PickerBuilder();
picker.addView(view);
picker.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);
picker.setOAuthToken(token);
picker.setAppId()
picker.setCallback(onDriveFileOpen);
picker = picker.build();
picker.setVisible(true);
}
}
function onDriveFileOpen(data) {
console.log(data);
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
console.log(fileId);
alert(data.docs[0].name);
}
}
</script>
<script async defer src="https://apis.google.com/js/api.js">
</script>
</body>
</html>

Why won't my Google Picker Window Appear in The Browser

I am building out the google picker for a project I am working on. However, the script below is what I have written for utilizing the Google Picker API, to open the picker in the page to allow users to drop items into the drive. I am trying to understand what is missing in the code functions that prevent the window from appearing.
Should I include this into a button to activate it?
<script>
function onApiload() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker');
}
function onAuthApiLoad(){
window.gapi.auth.authorize({
'client_id': '596875534635.apps.googleusercontent.com',
'scope': ['https://www.googleapis.com/auth/drive']
}, handleAuthResult);
}
var oauthToken;
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authReults.access_token;
createPicker();
}
}
function createPicker() {
var picker = new google.picker.PickerBuilder()
.addView(new google.picker.DocsUploadView())
.addView(new google.picker.DocsView())
.setAuthToken
.setDeveloperKey('AIzaSyBTsUe7i_eezFJ3ndIT8axJCR6IpksyLs8')
.build();
picker.setVisible(true);
}
</script>
<script src="https://apis.google.com/js/api.js?onload-onApiLoad">
</script>
You need to pass in the oauthToken variable to the setOAuthToken function call in your createPicker() function. Everything else looks fine (presuming that you are using the right credentials). So your createPicker() function should look like this:
function createPicker() {
var picker = new google.picker.PickerBuilder()
.addView( new google.picker.DocsUploadView() )
.addView( new google.picker.DocsView() )
.setOAuthToken( oauthToken )
.setDeveloperKey( 'AIzaSyBTsUe7i_eezFJ3ndIT8axJCR6IpksyLs8' )
.build();
// Render the picker model
picker.setVisible( true );
}

Categories

Resources