Genera azioni

Gli oggetti Action consentono di creare modelli il comportamento dei componenti aggiuntivi di Google Workspace. Definiscono cosa succede quando un utente interagisce con un widget (ad esempio un pulsante) in l'interfaccia utente del componente aggiuntivo.

Viene collegata un'azione a un widget specifico utilizzando un funzione di gestore widget, che definisce anche la condizione che attiva l'azione. Quando viene attivato, esegue un'azione funzione di callback. Alla funzione di callback viene passato un oggetto evento che contiene informazioni sulle interazioni lato client dell'utente. Devi implementare la funzione di callback e impostarla in modo che restituisca un oggetto di risposta specifico.

Ad esempio, supponi di voler creare un pulsante che crei e mostri una nuova scheda quando selezionato. Per farlo, devi creare un nuovo widget del pulsante e usare quello del pulsante funzione gestore setOnClickAction(action) per impostare la creazione di carte Action. La Action che definisci specifica uno script di Google Apps funzione di callback che viene eseguita quando l'utente fa clic sul pulsante. In questo caso, implementa la funzione di callback per creare la scheda che ti interessa e restituire un oggetto ActionResponse. L'oggetto di risposta indica al componente aggiuntivo di visualizzare la scheda creata dalla funzione di callback.

Questa pagina descrive le azioni del widget specifiche di Drive che puoi includere nei tuoi come componente aggiuntivo.

Aumentare le interazioni

I componenti aggiuntivi di Google Workspace che estendono Drive possono includere un'azione aggiuntiva del widget specifica per Drive. Questa azione richiede che la funzione di callback associata all'azione restituisca un oggetto di risposta specializzato:

Azione tentata La funzione di callback deve restituire
Richiedi l'accesso ai file per i file selezionati DriveItemsSelectedActionResponse

Per utilizzare queste azioni e questi oggetti di risposta dei widget, devono essere soddisfatte tutte le seguenti condizioni:

  • L'azione viene attivata quando l'utente ha selezionato uno o più elementi di Drive.
  • Il componente aggiuntivo include https://www.googleapis.com/auth/drive.file l'ambito Drive nel suo manifest.

Richiedere l'accesso ai file selezionati

L'esempio seguente mostra come creare un'interfaccia contestuale per Google Drive che si attiva quando l'utente seleziona uno o più elementi di Drive. L'esempio verifica ogni elemento per verificare se al componente aggiuntivo è stata concessa l'autorizzazione di accesso. Se non è così, utilizza un oggetto DriveItemsSelectedActionResponse per richiedere l'autorizzazione all'utente. Una volta concessa l'autorizzazione per un elemento, il componente aggiuntivo visualizza l'utilizzo della quota di Drive per quell'elemento.

/**
 * Build a simple card that checks selected items' quota usage. Checking
 * quota usage requires user-permissions, so this add-on provides a button
 * to request `drive.file` scope for items the add-on doesn't yet have
 * permission to access.
 *
 * @param e The event object passed containing contextual information about
 *    the Drive items selected.
 * @return {Card}
 */
function onDriveItemsSelected(e) {
  var builder =  CardService.newCardBuilder();

  // For each item the user has selected in Drive, display either its
  // quota information or a button that allows the user to provide
  // permission to access that file to retrieve its quota details.
  e['drive']['selectedItems'].forEach(
    function(item){
      var cardSection = CardService.newCardSection()
          .setHeader(item['title']);

      // This add-on uses the recommended, limited-permission `drive.file`
      // scope to get granular per-file access permissions.
      // See: https://developers.google.com/drive/api/v2/about-auth
      if (item['addonHasFileScopePermission']) {
        // If the add-on has access permission, read and display its
        // quota.
        cardSection.addWidget(
          CardService.newTextParagraph().setText(
              "This file takes up: " + getQuotaBytesUsed(item['id'])));
      } else {
        // If the add-on does not have access permission, add a button
        // that allows the user to provide that permission on a per-file
        // basis.
        cardSection.addWidget(
          CardService.newTextParagraph().setText(
              "The add-on needs permission to access this file's quota."));

        var buttonAction = CardService.newAction()
          .setFunctionName("onRequestFileScopeButtonClicked")
          .setParameters({id: item.id});

        var button = CardService.newTextButton()
          .setText("Request permission")
          .setOnClickAction(buttonAction);

        cardSection.addWidget(button);
      }

      builder.addSection(cardSection);
    });

  return builder.build();
}

/**
 * Callback function for a button action. Instructs Drive to display a
 * permissions dialog to the user, requesting `drive.file` scope for a
 * specific item on behalf of this add-on.
 *
 * @param {Object} e The parameters object that contains the item's
 *   Drive ID.
 * @return {DriveItemsSelectedActionResponse}
 */
function onRequestFileScopeButtonClicked (e) {
  var idToRequest = e.parameters.id;
  return CardService.newDriveItemsSelectedActionResponseBuilder()
      .requestFileScope(idToRequest).build();
}

/**
 * Use the Advanced Drive Service
 * (See https://developers.google.com/apps-script/advanced/drive),
 * with `drive.file` scope permissions to request the quota usage of a
 * specific Drive item.
 *
 * @param {string} itemId The ID of the item to check.
 * @return {string} A description of the item's quota usage, in bytes.
 */
function getQuotaBytesUsed(itemId) {
  try {
    return Drive.Files.get(itemId,{fields: "quotaBytesUsed"})
        .quotaBytesUsed + " bytes";
  } catch (e) {
    return "Error fetching how much quota this item uses. Error: " + e;
  }
}