JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
</script>
<div id="authorize-div" style="display: none">
<span>Authorize access to Google Apps Script Execution API</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
<div id="output">
</div>
CSS
table {
border-collapse: collapse;
}
td,
th {
padding: 10px;
border: 1px solid gray;
}
JavaScript
var CLIENT_ID = '262329801796-aq1qj4djf0o6sdfaac4bqr6nqqqvs3cc.apps.googleusercontent.com';
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
callScriptFunction();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* @param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize({
client_id: CLIENT_ID,
scope: SCOPES,
immediate: false
},
handleAuthResult);
return false;
}
function callScriptFunction() {
var scriptId = "MrufEVeGePOQy_RA3hF0dx7uYJESIqdA4"; // aka Project key
// Create an execution request object.
var request = {
'function': 'getData'
};
var op = gapi.client.request({
'root': 'https://script.googleapis.com',
'path': 'v1/scripts/' + scriptId + ':run',
'method': 'POST',
'body': request
});
op.execute(function(res) {
var htmlTable = '<table>';
res.response.result.forEach(function(row, idx, rows) {
if (idx == 0) {
htmlTable += '<tr><th>' + row.join('</th><th>') + '</th></tr>';
} else {
htmlTable += '<tr><td>' + row.join('</td><td>') + '</td></tr>';
}
});
htmlTable += '</table>';
document.getElementById('output').innerHTML = htmlTable;
});
}