I'm using Google Picker to get files from Google Drive.
I will be getting my Refresh Token and Access Token from my Database.
My old code which is working fine with User Authentication which asks for username and password for the first time.
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
function onGoogleApiLoad() {
gapi.load('auth', { 'callback': onGoogleAuthApiLoad });
gapi.load('picker');
}
function onGoogleAuthApiLoad() {
window.gapi.auth.authorize({
'client_id': 'MY_CLIENT_ID',
'scope': ['https://www.googleapis.com/auth/drive']
}, handleAuthResult);
}
var oGoogleauthToken;
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
debugger;
oGoogleauthToken = authResult.access_token;
createGooglePicker();
}
}
Now, I'm trying to open the Picker using the Access token by the following code because I don't want to ask for User Authentication any more.
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
var oGoogleauthToken = MY_TOKEN_FROM_DATABASE;
createGooglePicker();
function createGooglePicker() {
debugger;
var picker = new google.picker.PickerBuilder()
.addView(new google.picker.DocsView())
.setOAuthToken(oGoogleauthToken)
.setDeveloperKey('MY_DEVELOPER_KEY')
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.setCallback(GooglepickerCallback)
.build();
picker.setVisible(true);
}
But I'm getting an error like google is not defined.
Is there any way, I can do this?
Is there any thing, I need to do in the script reference file?
Related
I was trying to use Google App Script. My first attempt concern the capability to open a file picker and select a file from my Google Drive. To do this, I read th official documentation and I try to implement it. So I write the following application:
Code.gs
function doGet() {
return HtmlService
/*.createTemplateFromFile('index.html')
.evaluate();*/
.createHtmlOutputFromFile('index.html');
}
index.html
<!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">
// The Browser API key obtained from the Google API Console.
// Replace with your own Browser API key, or your own key.
var developerKey = "{{developer-key}}";
// The Client ID obtained from the Google API Console. Replace with your own Client ID.
var clientId = "{{client-id}}"
// Replace with your own project number from console.developers.google.com.
// See "Project number" under "IAM & Admin" > "Settings"
var appId = "{{project-number}}";
// 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() {
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.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())
.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);
}
}
</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=loadPicker"></script>
</body>
</html>
When I try to execute the code, after the authorization phase, I obtain the a blank screen and a blank dialog with the error: Failed to execute 'postMessage'. What is wrong? Thanks
Issue/Solution:
You're working within a iframe, where content is served from a different origin. You should use setOrigin on the picker builder.
Snippet:
var picker = new google.picker.PickerBuilder()
//...
.setOrigin(google.script.host.origin)
Reference:
Working with Picker API
File Open Dialog Code Sample
I have implemented a google file picker in HTML and JS. I have created a client credentials and in the verge of downloading the files from file picker. My code is
<!DOTYPE html>
<html>
<head>
<title>My website</title>
<script type="text/javascript">
// The Browser API key obtained from the Google API Console.
var developerKey = '############################';
// The Client ID obtained from the Google API Console. Replace with your own Client ID.
var clientId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
// Scope to use to access user's photos.
var scope = 'https://www.googleapis.com/auth/drive';
var appId = "1255s8a2s";
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth2', onAuthApiLoad);
gapi.load('picker', onPickerApiLoad);
gapi.client.load('drive', 'v2',handleClientLoad);
}
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(onAuthApiLoad,1);
}
function onAuthApiLoad() {
var authBtn = document.getElementById('auth');
authBtn.disabled = false;
authBtn.addEventListener('click', function() {
gapi.auth2.authorize({
client_id: clientId,
scope: scope
}, 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 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).
setOAuthToken(oauthToken).
setAppId(appId).
addView(view).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
var ids=[];
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var ln = data[google.picker.Response.DOCUMENTS];
for(i=0;i<ln.length;i++) {
ids[i] = data.docs[i].id;
gapi.client.drive.files.get({'fileId': ids[1]});
}
}
}
</script>
</head>
<body>
<h1> Welcome to detect the colours of your image </h1>
<p> Please upload required images. Let us detect what wonderful colours do your images have</p>
<form id="upload-form" action="{{ url_for('upload') }}" method = "POST" enctype="multipart/form-data">
<input type = "file" name="file" accept="image/*" multiple>
<input type="submit" value="upload">
</form>
<form method = "POST" action="/gdrive">
<button type="button" id="auth">upload from google</button>
</form>
<div id="result"></div>
<!-- The Google API Loader script. -->
<script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
</body>
</html>
After reading google drive javascript api gapi.client.drive.files undefined, I decided to add gapi.client.load('drive', 'v2', callback); in my code. However the result remains the same. I could not initialize the gapi.client, The drive api is enabled. I am new to Javascript, Can anyone please help me download the files using file ids. The File ids are stored in ids[] array in the code.
Thank you for trying to help me out
I have created a system where user selects files from their Google drive to be uploaded into Parse.
I have done so separately though, where I have one code that allows user to select an item from Google drive, and one that allows user to upload a file from their computer into parse.
Google drive (Using Google drive picker):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>eSnail Scan Upload Part 2</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'KEY';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
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().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
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 = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
</script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
That allows a user to upload a file into Parse (PDF):
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("ID", "ID");
function saveDocumentUpload(objParseFile)
{
var documentUpload = new Parse.Object("Scan");
documentUpload.set("Name", "");
documentUpload.set("DocumentName", objParseFile);
documentUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#myForm').bind("submit", function (e) {
e.preventDefault();
var fileUploadControl = $("#documentFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
var user_id = $('#user_id').val();
var address = $('#address').val();
parseFile.set('UserId', user_id);
parseFile.set('Address', address);
parseFile.save().then(
function () {
saveDocumentUpload(parseFile);
},
function (error) {
alert("error");
}
);
});
});
</script>
<body><form id='myForm'>
<input type="file" id="documentFileUpload">
<br/>
<input type="text" placeholder="UserID" id="user_id">
<br/>
<input type="text" placeholder="Address" id="address">
<br/>
<input type="submit" value="submit">
</form>
</body>
</HTML>
I am new to JavaScript and Google BigQuery, so please forgive my ignorance. I am trying to write a javascript to collect data from one of the public databases on BigQuery. I found an answer to this at Obtaining BigQuery data from JavaScript code (the code for which I have pasted below) but when I saved the file as .html, replaced the client id and project number with mine, and tried to run it, I get the Authorize button and the page title. I click the Authorize button, and it disappears, but no query is run. Is there something else I was supposed to replace or is there something else I need to make this work? I saved the file as a .html, perhaps I should have saved it with a different extension?
I tried all three ways of creating a client id in the Google developers console and all gave me the same behavior.
I'm sure its just something silly that I am forgetting, but any advice would be greatly appreciated.
Here is the code given by Ryan Boyd, which I am unable to get working properly(which is surely my fault):
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = '605902584318';
var client_id = '605902584318.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
Update: I opened the Developer Tools in Chrome and found this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin
provided ('file://') does not match the recipient window's origin
('null')
.
I tried editing in my Google Developer console as per these instructions: Google API in Javascript
Still same error.
Looks like you may need to add:
$('#query_button').show();
to the bottom of the auth() function
like so:
function auth() {
gapi.auth.authorize(config, function()
{
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
$('#query_button').show();
}
Searching for the error you got, I found this page:
Google API in Javascript
Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID. --#citizenslave
It turns out it was a combination of things. I had the Javascript origin not configured properly, I didn't have all the scopes needed for my query, and I couldn't just open the html file in a browser, I needed to create an HTTP server.
So I changed the code to be:
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
I fixed my Google Javascript Origins url to be http://localhost:8888/ and my Redirect uri to be http://localhost:8888/oauth2callback, opened a command prompt to run this command from the directory of my html file:
python -m SimpleHTTPServer 8888
and then went to localhost:8888 in my browser and clicked my html file there.
Thanks so much for all the feedback!
It worked perfectly! Now to change the query for my purposes!
I'm working on a simple javascript code I found here: http://googleappsdeveloper.blogspot.com/2011/12/using-new-js-library-to-unlock-power-of.html
It basically acquires authentication to a google Calendar and retrieves the list of events contained in it. I have registered my web application and obtained a client ID and API Key.
I'm facing this error: "Error: Origin mismatch", I'm running the javascript locally using localhost and I set my homepage in the google application registration to localhost as well.
any help would be immensely appreciated.
the code:
<html>
<body>
<div id='content'>
<h1>Events</h1>
<ul id='events'></ul>
</div>
<a href='#' id='authorize-button' onclick='handleAuthClick();'>Login</a>
<script>
var clientId = '506979856128.apps.googleusercontent.com';
var apiKey = 'AIzaSyAGbQAZQU0YNL8hK5EU69exIg7_sOg3JoA';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},
handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult) {
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('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
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);
}
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"> </script>
</body>
</html>
I got the same error origin mismatch today.after bit of search i got the reason.
While creating the Google Api Access,we have to specify Authorized Redirect URIs and Authorized Redirect URIs.
Now if you call the Login from URIs other than specified in Authorized Redirect URIs, error:Unknown Origin is thrown
FYI:I have seen that you are running the javascript locally using localhost.
It means that You have not added localhost uri to Authorized Redirect URIs.
But Don't waste your time doing that.Authorized Redirect URIs will not accept localhost uri.It's due to Chrome's same origin policy.and If you run chrome with the disable-web-security flag, it'll work locally too.
The problem of origin mismatch can be solved by taking care for Redirect URIs and Javascript Origins when creating Client ID in Google Developers Console.
The Javascript Origins should not end with /.
Example: http://example.com/ --> The correct format will be http://example.com.