Trying to rename all files in folder, nothing much, just want to add an prefix in all files, using Javascript. Getting error as: "Uncaught TypeError: gapi.client.drive.files.patch is not a function"
listFiles Function is able to fetch the file id and current name, but gapi.client.drive.files.patch throws above error.
Tried with gapi.client.drive.properties.patch but it also gave an error.!
Code:
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<p id="list" style="display: none;">Enter Folder ID:
<input type="text" id="listInput" size="40" />
<button id="list-button" onClick="listFiles();">Get List</button></p>
<pre id="content"></pre>
<script type="text/javascript">
var CLIENT_ID = '';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
var SCOPES = 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.scripts';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
var pre = document.getElementById('content');
var list = document.getElementById('list');
var listInput = document.getElementById('listInput');
var listButton = document.getElementById('list-button');
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
list.style.display = 'block';
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
list.style.display = 'none';
clearPre();
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function appendPre(message) {
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
function clearPre() {
pre.innerHTML = "";
}
function listFiles() {
clearPre();
appendPre('Getting Files List......');
gapi.client.drive.files.list({
'q' : "'" + listInput.value + "' in parents",
'orderBy' : 'name',
'pageSize': 1000,
'fields': "nextPageToken, files(id, name, parents, mimeType)"
}).then(function(response) {
clearPre();
var files = response.result.files;
console.log(files);
if (files && files.length > 0) {
var currentFile;
var currentFileId;
appendPre('Count: ' + files.length + ' Files:');
for (var i = 0; i < files.length; i++) {
currentFile = files[i].name;
currentFileId = files[i].id;
appendPre(currentFile);
alert(currentFileId + ' Rename ' + currentFile);
*********Getting Error here*********
var request = gapi.client.drive.files.patch({
'fileId': currentFileId,
'resource': {'title': 'Rename ' + currentFile}
});
request.execute(function(resp) {
console.log('New Title: ' + resp.title);
});
}
} else {
appendPre('No files found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js" nload="this.onload=function(){};handleClientLoad()" onreadystatechange="if this.readyState === 'complete') this.onload()">
</script>
I can see in your code that you are using V3.
gapi.client.drive.files.patch is deprecated in the said version, you can use Files: update instead, to update the desired filenames.
Or other way around, you can switch to V2 and use the code provided in the documentation.
/**
* Rename a file.
*
* #param {String} fileId <span style="font-size: 13px; ">ID of the file to rename.</span><br> * #param {String} newTitle New title for the file.
*/
function renameFile(fileId, newTitle) {
var body = {'title': newTitle};
var request = gapi.client.drive.files.patch({
'fileId': fileId,
'resource': body
});
request.execute(function(resp) {
console.log('New Title: ' + resp.title);
});
}
Appreciate the original question was Javascript and V2 of the Google Drive API...
Trying to use Python and V3, it took me a while to work out how to do this. The bit I was missing was the body={} keyword argument that you need to submit the name property.
Assuming you've already gotten the file_id you want to rename in a separate call, like this:
drive.files().update(
fileId=file_id,
supportsAllDrives='true',
body={'name': 'new name for this file'}
).execute()
After 3 attempts to use other folks NPM modules for Google Drive, I decided it was time to do my own and I was JUST adding mv() functionality so I had this fight and here's what I came up with and use in my library. It isn't public today and will change names, but if anyone wants to try a beta version, hit me up on twitter by this same name.
note:
You only need addParents and removeParents if you're "moving" a file and you only need name if you're actually going to rename it.
drive.files.update({
fileId: driveFileId,
addParents: commaStringOfParents,
removeParents: commaStringOfParents,
resource: { name: newFileName }
}, (err, res) => {
if (err) handleError(err);
let files = res.data
// Do stuff here
}
Related
I would like to access a public google drive folder and get all the images from it. This works, but I would like to be able to enter without having to login in a popup. I read that you can actually do this by using the .json file from a service account. But I haven't seen any code for this approach. Where and what should I change in this code? (I'm including the whole code because I don't know exactly where to initiate this service account authentication.)
<html>
<head>
<title>My Google Drive Images</title>
</head>
<body>
<h1>My Google Drive Images</h1>
<div id="image-container"></div>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = 'CLIENT_ID';
const API_KEY = 'API_KEY';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/drive';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
/**
* Callback after api.js is loaded.
*/
function gapiLoaded() {
gapi.load('client', initializeGapiClient);
}
/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function initializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
/**
* Enables user interaction after all libraries are loaded.
*/
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await listFiles();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
function listFiles() {
console.log("Listing files in folder");
gapi.client.drive.files.list({
"includeItemsFromAllDrives": true,
"supportsAllDrives": true,
"q": "trashed = false and parents in 'FOLDER_ID'"
}).then(function(response) {
console.log("Files listed successfully");
var files = response.result.files;
if (files && files.length > 0) {
console.log(files.length + " files found");
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fileId = file.id;
var fileUrl = "https://drive.google.com/u/0/uc?id=" + fileId;
var imgTag = document.createElement("img");
imgTag.src = fileUrl;
document.getElementById("image-container").appendChild(imgTag);
}
} else {
console.log("No files found.");
}
}, function(reason) {
console.log("Error listing files: " + reason.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>
I already tried changing the scopes and I read all that I could, but this topic is just not on the internet. The best case would be to don't use OAuth, but as I've read it's needed for accessing this API. Even the Google Drive API Reference only says this note, but it doesn't elaborate on this aspect:
Note: Authorization optional.
Could somebody please help me on this topic?
I would like to access a public google drive folder and get all the images from it.
If all you want to do is read it and its public, then you could just use an API Key.
I read that you can actually do this by using the .json file from a service account.
Client side JavaScript does not support service account authorization flow. You need to use implicit flow in and request authorization of a user to access the ir private data.
To use Service accounts you must use a server sided programing language
I have tried making a web application using Google Drive and Gmail APIs.
When I ask for Google Drive or Gmail permission, all works correctly, but when I try asking for both permissions , the program only asks for one of them (either Google Drive or Gmail).
This is the code which asks for Google Drive permissions, extracted from:https://developers.google.com/drive/api/v3/quickstart/js
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<p></p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '<YOUR_CLIENT_ID>';
var API_KEY = '<YOUR_API_KEY>';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listFiles();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print files.
*/
function listFiles() {
gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
}).then(function(response) {
appendPre('Files:');
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendPre(file.name + ' (' + file.id + ')');
}
} else {
appendPre('No files found.');
}
});
}
</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>
</body>
</html>
And this is the code which asks for Gmail permissions, extracted from:https://developers.google.com/gmail/api/quickstart/js
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<p></p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '<YOUR_CLIENT_ID>';
var API_KEY = '<YOUR_API_KEY>';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listLabels();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print all Labels in the authorized user's inbox. If no labels
* are found an appropriate message is printed.
*/
function listLabels() {
gapi.client.gmail.users.labels.list({
'userId': 'me'
}).then(function(response) {
var labels = response.result.labels;
appendPre('Labels:');
if (labels && labels.length > 0) {
for (i = 0; i < labels.length; i++) {
var label = labels[i];
appendPre(label.name)
}
} else {
appendPre('No Labels found.');
}
});
}
</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>
</body>
</html>
I have tried different ways to ask for both permissions, but no one of them has worked.
How do I ask for Gmail and Google Drive permissions at the same time?
PD: sorry for my English and for making a very long question :(
The difference between the two codes are the discovery docs and scopes used for the initiation of the gapi client
If you want to initialize a gapi client that it capable of performing both Gmail and Drive requests, you need to merge the respective discovery docs and scopes.
As stated in the comments of the code samples:
// Array of API discovery doc URLs for APIs used by the quickstart
and
// Authorization scopes required by the API; multiple scopes can be //
included, separated by spaces.
This means:
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest", "https://sheets.googleapis.com/$discovery/rest?version=v4"];
and
var SCOPES = "https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/spreadsheets.readonly";
Also, if the signIn is successful, either the function listFiles(); or listMajors(); is called, but to combine both functionalities, you probably want to call both functions (or merge them into one).
So in summary:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<p></p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '199656296815-7rivr6cr4oj1fhprdptrq9evi6gvrrji.apps.googleusercontent.com';
var API_KEY = 'AIzaSyCpC-SyaoUN95t8gANPgPQptEW-7B57aCI';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest", "https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/spreadsheets.readonly";
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listFiles();
listMajors();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print files.
*/
function listFiles() {
gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
}).then(function(response) {
appendPre('Files:');
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendPre(file.name + ' (' + file.id + ')');
}
} else {
appendPre('No files found.');
}
});
}
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
</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>
</body>
</html>
I have a problem with Google Calendar that I am unable to resolve. Here is the scenario: I had implemented it successfully using JavaScript as described in the quickstart guide
Now it just stopped working without changing anything.
Here is the code of my quickstart.html:
<!DOCTYPE html>
<html>
<head>
<title>Say hello using the People API</title>
<meta charset='utf-8' />
</head>
<body>
<p>Say hello using the People API.</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Autoriser </button>
<button id="signout-button" style="display: none;">se deconecter</button>
<div id="content"></div>
<pre id="output"></pre>
<script type="text/javascript">
console.log('im execusted');
var dateaud = localStorage.getItem("date1")
var jDate = new Date(dateaud);
var nd = jDate.toISOString();
var numdossier = localStorage.getItem("casenumber");
var notes = localStorage.getItem("notes");
var summary = numdossier + ' ' +notes ;
// Enter an API key from the Google API Console:
// https://console.developers.google.com/apis/credentials?project=_
var apiKey = 'mykey';
// cette clé est dispo via creer api key
// Enter a client ID for a web application from the Google API Console:
// https://console.developers.google.com/apis/credentials?project=_
// In your API Console project, add a JavaScript origin that corresponds
// to the domain where you will be running the script.
var clientId = 'myclientid';
// Enter one or more authorization scopes. Refer to the documentation for
// the API or https://developers.google.com/identity/protocols/googlescopes
// for details.
var scopes = 'https://www.googleapis.com/auth/calendar';
var auth2; // The Sign-In object.
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
function handleClientLoad() {
// Load the API client and auth library
gapi.load('client:auth2', initAuth);
}
function initAuth() {
gapi.client.setApiKey(apiKey);
gapi.auth2.init({
client_id: clientId,
scope: scopes
}).then(function () {
auth2 = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
auth2.isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(auth2.isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
makeApiCall();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
auth2.signIn();
}
function handleSignoutClick(event) {
auth2.signOut();
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var event = {
'summary': summary,
'description': notes,
'start': {
'dateTime': nd,
'timeZone': 'Africa/Casablanca'
},
'end': {
'dateTime': nd,
'timeZone': 'Africa/Casablanca'
}
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
request.execute(function(event) {
alert(nd);
appendPre('événement crée avec succée .: ' + event.htmlLink);
});
});
}
function appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
</script>
<script src="https://apis.google.com/js/api.js?onload=handleClientLoad"></script>
</body>
</html>
When I call this URL, filling the parameters out correctly for my event using this code:
<script>
function addcal(){
var date1=document.getElementById('date1').value;
var casenumber=document.getElementById("casenumber").innerText;
var notes=document.getElementById("notes").value;
var resultat=document.getElementById('resultat');
localStorage.setItem('date1', date1);
localStorage.setItem('casenumber', casenumber);
localStorage.setItem('notes', notes);
localStorage.setItem('resultat', resultat);
window.open('http://mywebsie.com/quickstart.html', 'newwindow', 'width=600, height=400');
}
</script>
I get a blank page, with no HTML code in it when showing source code. There are no JavaScript errors.
Can anyone help me with this?
good news
the issues was coming from nginx , on the server it's set as a proxy to apache , so desabling it solved my issue.
I have coded in asp, vb, c, etc in the past. I am now working on something in javascript inside google's HTML service.
I have allot of data that I am moving in and out of googles spreadsheets.
I have pulled plenty of data out of a spreadsheet by moving between the gs and html.
and wrote plenty of data using gs.
but with what I am trying to do I would really like to be able to us the SpreadsheetApp inside a script tag inside the html
, is this possible, I have yet been able to get it to work.
below is a test i am doing just to see where the code stops. and it stops at the spreadsheetapp.
function fnImport() {
var btn = document.getElementById('btnImport');
btn.value = "stage1";
var importselect = document.getElementById('importselect');
var seconddiv = document.getElementById('testdiv');
btn.value = "stage2";
var ss1 = SpreadsheetApp.openById("<i have actual id here>");
btn.value = "stage3";
for ( var i = 0; i < importselect.selectedOptions.length; i++) {
seconddiv.innerHTML = seconddiv.innerHTML + importselect.selectedOptions[i].value + '<br>';
}
};
</script>
is it possible to run spreadsheetapp inside the html this way.
thanks
Google has a Google Sheets JavaScript API for this:
<!DOCTYPE html>
<html>
<head>
<title>Google Sheets API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<p>Google Sheets API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '<YOUR_CLIENT_ID>';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listMajors();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
</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>
</body>
</html>
I am trying to upload file into my Google drive account using a webpage form. I select a file and I have to upload it into my Google drive using JavaScript API so, if any solution is have anyone the help me.
Here is one sample code for access Google drive, but I could not get the uploading file code.
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<script type="text/javascript">
var clientId = '######';
var apiKey = 'aaaaaaaaaaaaaaaaaaa';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = "https://www.googleapis.com/auth/drive";
// Use a button to handle authentication the first time.
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;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('drive', 'v2', function() {
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 fileInfo = document.createElement('li');
fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd ));
document.getElementById('content').appendChild(fileInfo);
}
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<p><b>These are 5 files from your GDrive :)</b></p>
<div id="content"></div>