Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Utilisez des objets Action pour intégrer un comportement interactif dans les modules complémentaires Google Workspace.
Les objets d'action définissent ce qui se passe lorsqu'un utilisateur interagit avec un widget (par exemple, un bouton) dans l'interface utilisateur du module complémentaire.
Ajouter une action à un widget
Pour associer une action à un widget, utilisez une fonction de gestionnaire de widget, qui définit également la condition qui déclenche l'action. Lorsqu'elle est déclenchée, l'action exécute une fonction de rappel désignée.
La fonction de rappel reçoit un objet d'événement qui contient des informations sur les interactions côté client de l'utilisateur. Vous devez implémenter la fonction de rappel et lui faire renvoyer un objet de réponse spécifique.
Exemple : Afficher une nouvelle carte lorsqu'un bouton est cliqué
Si vous souhaitez ajouter un bouton à votre module complémentaire qui crée et affiche une carte lorsque l'utilisateur clique dessus, procédez comme suit :
Pour définir une action de création de carte, ajoutez la fonction de gestionnaire de widget de bouton setOnClickAction(action).
Créez une fonction de rappel Apps Script à exécuter et spécifiez-la comme (action) dans la fonction de gestionnaire de widget. Dans ce cas, la fonction de rappel doit créer la carte souhaitée et renvoyer un objet ActionResponse. L'objet de réponse indique au module complémentaire d'afficher la fiche créée par la fonction de rappel.
L'exemple suivant montre comment créer un widget de bouton. L'action demande le champ d'application drive.file pour le fichier actuel au nom du module complémentaire.
/***AddsasectiontotheCardBuilderthatdisplaysa"REQUEST PERMISSION"button.*Whenit's clicked, the callback triggers file scope permission flow. This is used in*theadd-onwhenthehome-pagedisplaysbasicdata.*/functionaddRequestFileScopeButtonToBuilder(cardBuilder){varbuttonSection=CardService.newCardSection();//Iftheadd-ondoesnothaveaccesspermission,addabuttonthat//allowstheusertoprovidethatpermissiononaper-filebasis.varbuttonAction=CardService.newAction().setFunctionName("onRequestFileScopeButtonClickedInEditor");varbutton=CardService.newTextButton().setText("Request permission").setBackgroundColor("#4285f4").setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(buttonAction);buttonSection.addWidget(button);cardBuilder.addSection(buttonSection);}/***Callbackfunctionforabuttonaction.InstructsDocstodisplaya*permissionsdialogtotheuser,requesting`drive.file`scopeforthe*currentfileonbehalfofthisadd-on.**@param{Object}eTheparametersobjectthatcontainsthedocument’sID*@return{editorFileScopeActionResponse}*/functiononRequestFileScopeButtonClickedInEditor(e){returnCardService.newEditorFileScopeActionResponseBuilder().requestFileScopeForActiveDocument().build();
Interactions d'accès aux fichiers pour les API REST
Les modules complémentaires Google Workspace qui étendent les éditeurs et utilisent les API REST peuvent inclure une action de widget supplémentaire pour demander l'accès aux fichiers. Cette action nécessite que la fonction de rappel d'action associée renvoie un objet de réponse spécialisé :
Pour utiliser cette action de widget et cet objet de réponse, toutes les conditions suivantes doivent être remplies :
Le module complémentaire utilise des API REST.
Le module complémentaire présente la boîte de dialogue de portée du fichier de requête à l'aide de la méthode CardService.newEditorFileScopeActionResponseBuilder().requestFileScopeForActiveDocument().build();.
Le module complémentaire inclut le champ d'application de l'éditeur https://www.googleapis.com/auth/drive.file et le déclencheur onFileScopeGranted dans son fichier manifeste.
Demander l'accès au fichier pour le document actuel
Pour demander l'accès aux fichiers du document actuel, procédez comme suit :
Créez une fiche sur la page d'accueil qui vérifie si le module complémentaire dispose du champ d'application drive.file.
Dans les cas où le module complémentaire n'a pas reçu l'autorisation du champ d'application drive.file, créez un moyen de demander aux utilisateurs d'accorder l'autorisation du champ d'application drive.file pour le document actuel.
Exemple : Obtenir l'accès au document actuel dans Google Docs
L'exemple suivant crée une interface pour Google Docs qui affiche la taille du document actuel. Si le module complémentaire n'est pas autorisé à drive.file, il affiche un bouton permettant de lancer l'autorisation du champ d'application du fichier.
/***Buildasimplecardthatchecksselecteditems' quota usage. Checking*quotausagerequiresuser-permissions,sothisadd-onprovidesabutton*torequest`drive.file`scopeforitemstheadd-ondoesn't yet have*permissiontoaccess.**@parameTheeventobjectpassedcontaininginformationaboutthe*currentdocument.*@return{Card}*/functiononDocsHomepage(e){returncreateAddOnView(e);}functiononFileScopeGranted(e){returncreateAddOnView(e);}/***Forthecurrentdocument,displayeitheritsquotainformationor*abuttonthatallowstheusertoprovidepermissiontoaccessthat*filetoretrieveitsquotadetails.**@parameTheeventcontaininginformationaboutthecurrentdocument*@return{Card}*/functioncreateAddOnView(e){vardocsEventObject=e['docs'];varbuilder=CardService.newCardBuilder();varcardSection=CardService.newCardSection();if(docsEventObject['addonHasFileScopePermission']){cardSection.setHeader(docsEventObject['title']);//Thisadd-onusestherecommended,limited-permission`drive.file`//scopetogetgranularper-fileaccesspermissions.//See:https://developers.google.com/drive/api/v2/about-auth//Iftheadd-onhasaccesspermission,readanddisplayitsquota.cardSection.addWidget(CardService.newTextParagraph().setText("This file takes up: "+getQuotaBytesUsed(docsEventObject['id'])));}else{//Iftheadd-ondoesnothaveaccesspermission,addabuttonthat//allowstheusertoprovidethatpermissiononaper-filebasis.cardSection.addWidget(CardService.newTextParagraph().setText("The add-on needs permission to access this file's quota."));varbuttonAction=CardService.newAction().setFunctionName("onRequestFileScopeButtonClicked");varbutton=CardService.newTextButton().setText("Request permission").setOnClickAction(buttonAction);cardSection.addWidget(button);}returnbuilder.addSection(cardSection).build();}/***Callbackfunctionforabuttonaction.InstructsDocstodisplaya*permissionsdialogtotheuser,requesting`drive.file`scopeforthe*currentfileonbehalfofthisadd-on.**@param{Object}eTheparametersobjectthatcontainsthedocument’sID*@return{editorFileScopeActionResponse}*/functiononRequestFileScopeButtonClicked(e){returnCardService.newEditorFileScopeActionResponseBuilder().requestFileScopeForActiveDocument().build();}
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/07/25 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/07/25 (UTC)."],[[["\u003cp\u003eGoogle Workspace add-ons use Action objects to define interactive behavior triggered by user interactions with UI widgets.\u003c/p\u003e\n"],["\u003cp\u003eAn action's callback function executes when triggered and receives an event object containing interaction details, requiring a specific response object to be returned.\u003c/p\u003e\n"],["\u003cp\u003eAdd-ons extending Editors and using REST APIs can request file access using a widget action with a specialized response object returned by its callback function.\u003c/p\u003e\n"],["\u003cp\u003eRequesting file access involves building a homepage card to check for \u003ccode\u003edrive.file\u003c/code\u003e scope and providing a way for users to grant this scope if needed.\u003c/p\u003e\n"]]],["Action objects enable interactive behavior in Google Workspace add-ons by defining responses to user interactions with widgets. To implement actions, you must define a widget handler function that triggers a callback function upon a specific condition. This callback function then receives an event object with client-side interaction data and must return a specific response object. For file access, add-ons use a specialized response object, `EditorFileScopeActionResponse`, and need `drive.file` scope in the manifest.\n"],null,["# Editor actions\n\nUse [Action](/workspace/add-ons/concepts/actions) objects to build interactive\nbehavior into Google Workspace add-ons.\n\nAction objects define what happens when a user interacts with a widget\n(for example, a button) in the add-on UI.\n\nAdd an action to a widget\n-------------------------\n\nTo attach an action to a widget, use a [widget handler function](/workspace/add-ons/concepts/actions#widget_handler_functions),\nwhich also defines the condition that triggers the action. When triggered, the\naction executes a designated [callback function](/workspace/add-ons/concepts/actions#callback_functions).\nThe callback function is passed an [event object](/workspace/add-ons/concepts/event-objects)\nthat carries information about the user's client-side interactions. You must\nimplement the callback function and have it return a specific response object.\n\n### Example: Display a new card when a button is clicked\n\nIf you want to add a button to your add-on that builds and displays a new card\nwhen clicked, follow the steps below:\n\n1. Create a button [widget](/workspace/add-ons/concepts/widgets#user_interaction_widgets).\n2. To set a card-building action, add the button widget handler function [`setOnClickAction(action)`](/apps-script/reference/card-service/text-button#setOnClickAction(Action)).\n3. Create an Apps Script callback function to execute and specify it as the [`(action)`](/apps-script/reference/card-service/text-button#setOnClickAction(Action)) within the widget handler function. In this case, the callback function should build the card you want and return an [`ActionResponse`](/apps-script/reference/card-service/action-response) object. The response object tells the add-on to display the card the callback function built.\n\nThe following example shows the creation of a button widget. The action requests\nthe `drive.file` scope for the current file on behalf of the add-on. \n\n```gdscript\n/**\n * Adds a section to the Card Builder that displays a \"REQUEST PERMISSION\" button.\n * When it's clicked, the callback triggers file scope permission flow. This is used in\n * the add-on when the home-page displays basic data.\n */\nfunction addRequestFileScopeButtonToBuilder(cardBuilder) {\n var buttonSection = CardService.newCardSection();\n // If the add-on does not have access permission, add a button that\n // allows the user to provide that permission on a per-file basis.\n var buttonAction = CardService.newAction()\n .setFunctionName(\"onRequestFileScopeButtonClickedInEditor\");\n\n var button = CardService.newTextButton()\n .setText(\"Request permission\")\n .setBackgroundColor(\"#4285f4\")\n .setTextButtonStyle(CardService.TextButtonStyle.FILLED)\n .setOnClickAction(buttonAction);\n\n buttonSection.addWidget(button);\n cardBuilder.addSection(buttonSection);\n}\n\n/**\n * Callback function for a button action. Instructs Docs to display a\n * permissions dialog to the user, requesting `drive.file` scope for the \n * current file on behalf of this add-on.\n *\n * @param {Object} e The parameters object that contains the document's ID\n * @return {editorFileScopeActionResponse}\n */\nfunction onRequestFileScopeButtonClickedInEditor(e) {\n return CardService.newEditorFileScopeActionResponseBuilder()\n .requestFileScopeForActiveDocument().build();\n```\n\nFile access interactions for REST APIs\n--------------------------------------\n\nGoogle Workspace add-ons that extend the Editors and use REST APIs can include an\nadditional widget action to request file access. This action requires the\nassociated action callback function to return a specialized response object:\n\n| Action attempted | Callback function should return |\n|---------------------------------------------------------------------------------------|---------------------------------|\n| [Request file access for current_document](#request_file_access_for_current_document) | `EditorFileScopeActionResponse` |\n\nTo make use of this widget action and response object, all of the following must\nbe true:\n\n- The add-on uses REST APIs.\n- The add-on presents the request file scope dialog using the `CardService.newEditorFileScopeActionResponseBuilder().requestFileScopeForActiveDocument().build();` method.\n- The add-on includes the `https://www.googleapis.com/auth/drive.file` editor scope and `onFileScopeGranted` trigger in its manifest.\n\n### Request file access for current document\n\nTo request file access for the current document, follow these steps:\n\n1. Build a homepage card that checks whether the add-on has `drive.file` scope.\n2. For cases where the add-on hasn't been granted `drive.file` scope, build a way to request that users grant `drive.file` scope for the current document.\n\n#### Example: Get current document access in Google Docs\n\nThe following example builds an interface for Google Docs that displays the size\nof the current document. If the add-on doesn't have `drive.file` authorization,\nit displays a button to initiate the file scope authorization. \n\n /**\n * Build a simple card that checks selected items' quota usage. Checking\n * quota usage requires user-permissions, so this add-on provides a button\n * to request `drive.file` scope for items the add-on doesn't yet have\n * permission to access.\n *\n * @param e The event object passed containing information about the\n * current document.\n * @return {Card}\n */\n function onDocsHomepage(e) {\n return createAddOnView(e);\n }\n\n function onFileScopeGranted(e) {\n return createAddOnView(e);\n }\n\n /**\n * For the current document, display either its quota information or\n * a button that allows the user to provide permission to access that\n * file to retrieve its quota details.\n *\n * @param e The event containing information about the current document\n * @return {Card}\n */\n function createAddOnView(e) {\n var docsEventObject = e['docs'];\n var builder = CardService.newCardBuilder();\n\n var cardSection = CardService.newCardSection();\n if (docsEventObject['addonHasFileScopePermission']) {\n cardSection.setHeader(docsEventObject['title']);\n // This add-on uses the recommended, limited-permission `drive.file`\n // scope to get granular per-file access permissions.\n // See: https://developers.google.com/drive/api/v2/about-auth\n // If the add-on has access permission, read and display its quota.\n cardSection.addWidget(\n CardService.newTextParagraph().setText(\n \"This file takes up: \" + getQuotaBytesUsed(docsEventObject['id'])));\n } else {\n // If the add-on does not have access permission, add a button that\n // allows the user to provide that permission on a per-file basis.\n cardSection.addWidget(\n CardService.newTextParagraph().setText(\n \"The add-on needs permission to access this file's quota.\"));\n\n var buttonAction = CardService.newAction()\n .setFunctionName(\"onRequestFileScopeButtonClicked\");\n\n var button = CardService.newTextButton()\n .setText(\"Request permission\")\n .setOnClickAction(buttonAction);\n\n cardSection.addWidget(button);\n }\n return builder.addSection(cardSection).build();\n }\n\n /**\n * Callback function for a button action. Instructs Docs to display a\n * permissions dialog to the user, requesting `drive.file` scope for the\n * current file on behalf of this add-on.\n *\n * @param {Object} e The parameters object that contains the document's ID\n * @return {editorFileScopeActionResponse}\n */\n function onRequestFileScopeButtonClicked(e) {\n return CardService.newEditorFileScopeActionResponseBuilder()\n .requestFileScopeForActiveDocument().build();\n }"]]