I’m working this Google Workspace Add-on app, I’m trying to get a function that sets the appropriate function for calling the document id depending on if it’s called in the context of drive, docs, sheets, etc.
function checkContext(event){
var itemId;
Logger.log(event)
if (DocumentApp.getActiveDocument().getId() != null && DocumentApp.getActiveDocument().getId() != undefined)
{
itemId = DocumentApp.getActiveDocument().getId();
Logger.log(itemId);
}
else if (e.drive.selectedItems[0].id != null && e.drive.selectedItems[0].id != undefined){
var itemId = e.drive.selectedItems[0].id;
Logger.log(itemId);
}
else if (SpreadsheetApp.getActive().getId() != null && SpreadsheetApp.getActive().getId() != undefined){
var itemId = SpreadsheetApp.getActive().getId();
Logger.log(itemId);
}
else {
var itemId = SlidesApp.getActivePresentation().getId();
Logger.log(itemId);
}
As you can see, I’ve attempted to achieve this with a nested if statement, where the itemId
variable is set to the appropriate context depending on which getId() does NOT fail. Despite my best efforts, I always get the
TypeError: Cannot read property ‘getId’ of null
error every time the my function is triggered.
This is the solution I ended up with, using Cooper’s insight about
commonEventObjects
. This function returns the a string for getting a document ID in the appropriate context. The returned string can then be run witheval()
to return a doc id in function with the sameevent
.