I try of a dev solution for my company and I’m stuck with API of google sheets. I trying of write a page of googlesheets and my code no run without show me any error. I will greatfull for your asist.
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = '417439781945-jtcarehtqmqscff6bdhd18dcp9tgi83m.apps.googleusercontent.com';
const API_KEY = 'AIzaSyDubc8Tb2qI9NUNPg8ZNFQ91NkfUqzhSO4';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/spreadsheets';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('gapi').addEventListener("load", gapiLoaded);
document.getElementById('gis').addEventListener("load", gisLoaded);
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 listMajors();
};
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';
}
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
async function listMajors() {
let response;
try {
// Fetch first 10 files
response = await gapi.client.sheets.spreadsheets.values.update({
spreadsheetId: '1qO9JaCVAw4ezMljdN0tjI1hxx5tnctMd7e8_B3i4Tpc',
range: 'Trabajos!A2:D',
});
} catch (err) {
console.error(err);
return;
}
const range = response.result;
if (!range || !range.values || range.values.length == 0) {
console.warn('No se encontraron valores');
return;
}
const macAddress = getMacAddress();
const newDate = newDateNow();
range.values.forEach( async(trabajo) => {
const [numerotrabajo, responsable, fecha] = trabajo;
await enviarTrabajoConDatosExtras(numerotrabajo, responsable, macAddress, newDate)
});
}
function getMacAddress() {
if (window.navigator.userAgent.indexOf("Mac") > 0) {
return window.navigator.hardwareConcurrency;
} else {
return "No disponible";
}
}
function newDateNow() {
const now = new Date();
const fecha = now.toISOString().split('T')[0];
const hora = now.toISOString().split('T')[1].split('.')[0];
return `${fecha} ${hora}`;
}
async function enviarTrabajoConDatosExtras(numerotrabajo, responsable, macAddress, newDate) {
console.log('Enviando trabajo:', numerotrabajo, responsable, macAddress, newDate);
const spreadsheetId = '1qO9JaCVAw4ezMljdN0tjI1hxx5tnctMd7e8_B3i4Tpc';
const range = 'Trabajos!A:D';
const values = [
[numerotrabajo, macAddress, newDate]
];
try {
const response = await gapi.client.sheets.spreadsheets.values.append({
spreadsheetId: spreadsheetId,
range: range,
valueInputOption: 'RAW',
insertDataOption: 'INSERT_ROWS',
resource: {
values: values
}
});
console.log('Trabajo enviado con éxito:', response);
} catch (error) {
console.error('Error al enviar el trabajo:', error);
}
}
and the button the inicialize session in google disappeared too.
I try of inicialize session en google and write a document in googlesheets, me and other three persons inicialize sesion without problem.
