'Executing a Google App Script from a Chrome Extension using REST API
I have a Google App Script bounded to a Google doc and deployed as an API executable. This provides me with an API end-point in the following format.
https://script.googleapis.com/v1/scripts/<ScriptId>:run
Now, I want to hit this API from the background.js file in my Chrome Extension project. I'm unable to find a resource which elucidates all the steps required in doing so.
Thus far I have set the project ID equal to the project Id being used for my chrome extension project. I get an OAuth token using chrome.identity.getAuthToken and add it in the header before hitting the API above.
I essentially want the script to return the cursor's surroundTextOffset back to my chrome extension. The script just has one function:
function myFunction() {
let cursor = DocumentApp.getActiveDocument().getCursor();
if(cursor){
console.log(cursor.getSurroundingTextOffset());
return cursor.getSurroundingTextOffset();
}else{
console.log("cursor", cursor);
}
}
The API request from my Chrome Extension looks like this:
let fetchIndex = () => {
chrome.identity.getAuthToken({ interactive: true }, (token) => {
let init = {
method: "POST",
async: true,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json",
},
body: JSON.stringify({
function: "myFunction",
parameters: [],
devMode: true,
}),
};
fetch(
"https://script.googleapis.com/v1/scripts/<ScriptId>:run",
init
).then((response) => {
return response.json
}).then((data)=>{console.log("data", data});
});
};
When I run the the script inside Google's text-editor it runs perfectly and outputs the index position in the console. When I try to make an API hit from background.js via the code above it returns and error object, with the following details
@type: "type.googleapis.com/google.apps.script.v1.ExecutionError"
errorMessage: "TypeError: Cannot read property 'getSurroundingTextOffset' of null"
errorType: "ScriptError"
I suspect there might be an issue with the request's body.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
