Trying to get if statement to determine 'context' of addon app

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;
   if (DocumentApp.getActiveDocument().getId() != null && DocumentApp.getActiveDocument().getId() != undefined)
      itemId = DocumentApp.getActiveDocument().getId();
  else if ([0].id != null &&[0].id != undefined){  
    var itemId =[0].id;

  else if (SpreadsheetApp.getActive().getId() != null && SpreadsheetApp.getActive().getId() != undefined){  
    var itemId = SpreadsheetApp.getActive().getId();

  else {  
    var itemId = SlidesApp.getActivePresentation().getId();


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.

99 thoughts on “Trying to get if statement to determine 'context' of addon app”

Leave a Comment