I’m trying to run a script remotely as per the instructions at https://developers.google.com/apps-script/api/how-tos/execute. The script shares the same GCP project with the web application and has already been implemented as an executable API. The GCP project already has the necessary credentials to run, but I can't run the script remotely:
API executable (URL): https://script.googleapis.com/v1/scripts/AKf...JYC:run
OAuth 2.0 Client IDs: {"web":{"client_id":"903...h7l.apps.googleusercontent.com","project_id":"upl...615","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_p..."]}}
Here is my code:
<div class="group group-xl offset-top-20 offset-sm-top-50">
<button id="button" class="btn btn-icon btn-icon-left btn-primary btn-lg btn-anis-effect" data-caption-animate="fadeInUp" data-caption-delay="1200">My Button</button>
</div>
<script>
function myFunction() {
const options = {
"headers": {
"web": {
"client_id": "903...h7l.apps.googleusercontent.com",
"project_id": "upl...615",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "ZPg...aHJ",
"redirect_uris": [
"https://www.myweb.com/button.html"
],
"javascript_origins": [
"https://www.myweb.com"
]
}
}
"method": "post"
};
UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/AKf...JYC:run", options);
}
document.getElementById("button").onclick = myFunction;
</script>
Maybe someone can give me a little light on this...
Hi!
Could you share the message of issue you're received.
No message appears, it seems as if UrlFetchApp doesn't work.
OK. As I can see there is no 'function' key option. Look at the request body https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run#request-body
{
"function": string,
"parameters": [
value
],
"sessionState": string,
"devMode": boolean
}
Instead a fetch call I prefer the gapi client. It is simple for use:
gapi.client.script.scripts
.run({
scriptId:
'Deployment ID',
resource: {
function: 'myFumctionName',
parameters: [1,2,3]
},
})
.then((res) => {
console.log('OK. The function is excecuted');
})
.catch((err) => console.error(err));