2

I am building a Google Workspace add-on for Google Sheets and I'm trying to show a dialog using a card built by the CardService but I get the following error message.

TypeError: Cannot read properties of undefined (reading 'newCardHeader')

It appears the CardService object is undefined?

What am I doing wrong?

Code.gs

const ui = SpreadsheetApp.getUi();

const onOpen = e => {
  ui.createAddonMenu()
    .addItem( 'Help', 'showHelp', )
    .addToUi();
}

const buildCard = () => {
  const header = CardService.newCardHeader()
    .setTitle( "CardTitle", );
  const card = CardService.newCardBuilder()
    .setHeader( header, )
    .build();
  return card;
}

const showHelp = () => {
  const card = buildCard();
  ui.showDialog( card, );
}

Rubén
  • 34,714
  • 9
  • 70
  • 166
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
  • 1
    What is the addon type - editor or workspace? Which line is throwing the error? – TheMaster Jan 24 '23 at 08:19
  • @TheMaster The error has now changed and indicating it's happening on the line attempting to read `.newCardHeader()` – Let Me Tink About It Jan 24 '23 at 10:13
  • @TheMaster Actually, I think you might have solved it. When you asked whether it's an editor add-on or a workspace add-on. I guess I thought it was a workspace add-on but, in fact, it might have only been an editor add-on as I am writing the script in the script files bound to a Google Sheet. And that might be what's preventing the `CardService` from working? Does that sound correct? – Let Me Tink About It Jan 24 '23 at 10:13
  • 1
    That sounds accurate. – TheMaster Jan 24 '23 at 10:57
  • 1
    Related: https://stackoverflow.com/q/74696713/1595451 – Rubén Jan 24 '23 at 17:52

1 Answers1

2

Summary from comments:

@TheMaster Actually, I think you might have solved it. When you asked whether it's an editor add-on or a workspace add-on. I guess I thought it was a workspace add-on but, in fact, it might have only been an editor add-on as I am writing the script in the script files bound to a Google Sheet. And that might be what's preventing the CardService from working?

So, make sure the add-on is a Google Workspace add-on and the code is written in a standalone script. If the script is written in the code editors bound to a Google Sheet, then the CardService won't work as the CardService is only available to Google Workspace add-ons and not Google Editor add-ons.

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
  • 1
    Google Workspace add-on code could be included in bounded scripts, just avoid using the Card Service with Class Ui (used to create dialogs and sidebars together with the HTML Service) – Rubén Jan 24 '23 at 17:39