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;
  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.

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

  1. 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 with eval()to return a doc id in function with the same event.

    function serveDocCall(event){
      var context = event.commonEventObject.hostApp
      var docCall; 
      if (context == "DOCS")
       {docCall = 'DocumentApp.getActiveDocument().getId()';
          Logger.log(docCall);}
      else if (context == "DRIVE"){  
        var docCall = 'event.drive.selectedItems[0].id';
              Logger.log(docCall);}
      else if (context == "SHEETS"){  
        var docCall = 'SpreadsheetApp.getActive().getId()';
              Logger.log(docCall);}
      else {  
        var docCall = 'SlidesApp.getActivePresentation().getId()';
              Logger.log(docCall);}
      return docCall;
    }
    Reply

Leave a Comment