I have a Google script which modifies the content of a google spreadsheet (it's not the final script of course), but I have a problem to run this simple script from a google chrome extension. Here is the script attached to my spreadsheet :
function insertData(parameters) {
var spreadsheet = SpreadsheetApp.openByUrl(THE_URL_OF_THE_SPREADSHEET)
spreadsheet.getRange('A5').activate();
spreadsheet.getCurrentCell().setValue(parameters.data1);
spreadsheet.getRange('B5').activate();
spreadsheet.getCurrentCell().setValue(parameters.data2);
}
I deployed this script both as a web app (execute as me + access to everyone, even anonymous) and as an executable API (access to anyone).
Then I tried this JS script to run my google script, from a google chrome extension, using this code that I got from an google chrome extension example:
sendDataToExecutionAPICallback: function() {
post({ 'url': 'https://script.googleapis.com/v1/scripts/' + SCRIPT_ID + ':run',
'callback': obj.executionAPIResponse,
'token': 'MY_GENERATED_TOKEN'
'request': {
'function': 'insertData',
'parameters': {
'data1': 'ok1 from script',
'data2': 'ok2 from script'
},
'devMode': true
}
});
},
executionAPIResponse: function(response){
var obj = this;
var info;
if (response.response.result.status == 'ok'){
info = 'Data has been entered';
} else {
info = 'Error...';
}
obj.displayMessage(info);
}
And I have this post function :
function post(options) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// JSON response assumed. Other APIs may have different responses.
options.callback(JSON.parse(xhr.responseText));
} else if(xhr.readyState === 4 && xhr.status !== 200) {
console.log('post', xhr.readyState, xhr.status, xhr.responseText);
}
};
xhr.open('POST', options.url, true);
// Set standard Google APIs authentication header.
xhr.setRequestHeader('Authorization', 'Bearer ' + options.token);
xhr.send(JSON.stringify(options.request));
}
And when I call the sendDataToExecutionAPICallback
function, I got this auth error:
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
EDIT1: After generating a token, and added it to my code, I have this error:
"error": {
"code": 403,
"message": "The caller does not have permission",
"status": "PERMISSION_DENIED"
}
access to everyone, even anonymous
, then there is no point in using OAuth, it's not needed. – Alan WellsinsertData()
in GAS. But you are deploying both Web Apps and executable API. And it seems that your current script uses the executable API. Can I ask you about the method you want to use? By this, I think that your script can be modified. – Tanaike