Home:ALL Converter>Run a Google Apps Script using Javascript

Run a Google Apps Script using Javascript

Ask Time:2021-09-11T23:00:49         Author:Wardiam

Json Formatter

I have a command in cURL that allows me to run a Google Apps Script:

curl -X POST \
-H 'Authorization: Bearer ### access token ###' \
-H "Content-Type: application/json" \
-d '{"function": "##function name##", "parameters": ["##MainDocID##", ["##Doc1ID##","##Doc2ID##","##Doc3ID##"]], devMode: false}' \
"https://script.googleapis.com/v1/scripts/### script ID ###:run"

This script calls a function that is responsible for creating a folder in Google Drive and copying into the folder an edited and modified sheet file with certain values. The script works perfectly if I run it from the terminal.

I'm creating a web application and I want to include this script in a button that when clicked triggers the Apps Script function. To do this I want to convert this cURL command to javascript. I have used this converter (REQBIN) and got this code but no matter how many times I run it, it does not work correctly.

Converted javascript code:

var url = "https://script.googleapis.com/v1/scripts/### script ID ###:run";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Authorization", "Bearer ### access token ###");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
   if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
   }};

var data = '{"function": "##function name##", "parameters": ["##MainDocID##", ["##Doc1ID##","##Doc2ID##","##Doc3ID##"]], devMode: false}';

xhr.send(data);

After creating the button and adding the javascript code, I have tested if it works but it doesn't because I check in Google Drive and the folder has not been created and the file I edit has not been copied. I have not been able to find out the exact error. From the web browser (client side) I get the response code '200' and in Google Cloud (logging operations), I get nothing but the only sure thing is that the function has not been executed.

Why is it not working?. Is the javascript code correct?. Could anyone help me, please?.

Thank you very much, Wardiam

Author:Wardiam,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69144139/run-a-google-apps-script-using-javascript
yy