Unable to get cursor position from Google Doc using the App Script Web App URL in browser extension

5 views
Skip to first unread message

Ronak Bhandari

unread,
Jul 26, 2024, 3:31:49 PM (16 hours ago) Jul 26
to Chromium Extensions
Hi. I am trying to get the cursor position from the google doc in my browser extension. I have created an App Script and deployed it as a Web App with the below app configuration.
After placing the cursor, when I trigger the function from browser extension, the response is null. I checked the same responses in the App Script for that trigger using Logger and got null there also.

{ "dependencies": {
"enabledAdvancedServices": [
{
"userSymbol": "Docs",
"version": "v1",
"serviceId": "docs"
}
]
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"webapp": {
"executeAs": "USER_DEPLOYING",
"access": "ANYONE_ANONYMOUS"
} }

Below is the sample code from the App Script 

function doPost(e) {
console.log(JSON.parse(e.postData.contents).documentId);
const doc = DocumentApp.openById(JSON.parse(e.postData.contents).documentId);
var cursor = doc.getCursor();
// var cursor = DocumentApp.getActiveDocument().getCursor();
Logger.log(cursor);
if (cursor) {
var position = cursor.getSurroundingTextOffset();
return ContentService.createTextOutput(JSON.stringify({ position: position }))
.setMimeType(ContentService.MimeType.JSON);
// var element = cursor.getElement();
// var offset = cursor.getOffset();
// Logger.log('Cursor is at offset ' + offset + ' in this element: ' + element);
} else {
var selection = doc.getSelection();
Logger.log(selection);
if (selection) {
var elements = selection.getRangeElements();
if (elements.length > 0) {
var element = elements[0];
var position = element.getStartOffset();
return ContentService.createTextOutput(JSON.stringify({ position: position }))
.setMimeType(ContentService.MimeType.JSON);
}
}
return ContentService.createTextOutput(JSON.stringify({ position: -1 }))
.setMimeType(ContentService.MimeType.JSON);

// Logger.log('Cannot find cursor.');
// return ContentService.createTextOutput(JSON.stringify({ position: -1 }))
// .setMimeType(ContentService.MimeType.JSON);
}
}

Below is the sample code from by content scripts
fetch(url, {
method: 'POST',
body: JSON.stringify({
documentId: documentId,
}),
}).then((res) => res.json()).then((data) => {
console.log(data);
}).catch((err) => {
console.log(err)
});


What could possibly go wrong here?

--
Regards,
Ronak Bhandari
Reply all
Reply to author
Forward
0 new messages