Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Các đối tượng Action cho phép bạn tạo hành vi tương tác trong các tiện ích bổ sung của Google Workspace. Chúng xác định những gì xảy ra khi người dùng tương tác với một tiện ích (ví dụ: một nút) trong giao diện người dùng của tiện ích bổ sung.
Một thao tác được đính kèm vào một tiện ích nhất định bằng cách sử dụng hàm trình xử lý tiện ích, hàm này cũng xác định điều kiện kích hoạt thao tác. Khi được kích hoạt, thao tác này sẽ thực thi một hàm gọi lại được chỉ định.
Hàm gọi lại được truyền một đối tượng sự kiện mang thông tin về các hoạt động tương tác phía máy khách của người dùng. Bạn phải triển khai hàm gọi lại và yêu cầu hàm này trả về một đối tượng phản hồi cụ thể.
Ví dụ: giả sử bạn muốn một nút tạo và hiển thị thẻ mới khi được nhấp vào. Để làm việc này, bạn phải tạo một tiện ích nút mới và sử dụng hàm trình xử lý tiện ích nút setOnClickAction(action) để đặt Action tạo thẻ. Action mà bạn xác định sẽ chỉ định một hàm gọi lại Apps Script thực thi khi người dùng nhấp vào nút. Trong trường hợp này, bạn sẽ triển khai hàm callback để tạo thẻ mà bạn muốn và trả về một đối tượng ActionResponse. Đối tượng phản hồi yêu cầu tiện ích bổ sung hiển thị thẻ mà hàm gọi lại đã tạo.
Trang này mô tả các thao tác cụ thể của tiện ích trên Drive mà bạn có thể đưa vào tiện ích bổ sung.
Thúc đẩy lượt tương tác
Các tiện ích bổ sung của Google Workspace mở rộng Drive có thể bao gồm một thao tác bổ sung của tiện ích dành riêng cho Drive. Hành động này yêu cầu hàm gọi lại của hành động được liên kết trả về một đối tượng phản hồi chuyên biệt:
Để sử dụng các thao tác tiện ích và đối tượng phản hồi này, tất cả những điều sau đây phải đúng:
Thao tác này được kích hoạt khi người dùng chọn một hoặc nhiều mục trên Drive.
Tiện ích bổ sung này có https://www.googleapis.com/auth/drive.filephạm vi Drive trong tệp kê khai.
Yêu cầu quyền truy cập vào tệp đối với các tệp đã chọn
Ví dụ sau đây minh hoạ cách tạo một giao diện theo ngữ cảnh cho Google Drive, được kích hoạt khi người dùng chọn một hoặc nhiều mục trên Drive. Ví dụ này kiểm tra từng mục để xem liệu tiện ích bổ sung đã được cấp quyền truy cập hay chưa; nếu chưa, tiện ích bổ sung sẽ sử dụng một đối tượng DriveItemsSelectedActionResponse để yêu cầu người dùng cấp quyền đó. Sau khi bạn cấp quyền cho một mục, tiện ích bổ sung sẽ hiển thị hạn mức sử dụng Drive của mục đó.
/***Buildasimplecardthatchecksselecteditems' quota usage. Checking*quotausagerequiresuser-permissions,sothisadd-onprovidesabutton*torequest`drive.file`scopeforitemstheadd-ondoesn't yet have*permissiontoaccess.**@parameTheeventobjectpassedcontainingcontextualinformationabout*theDriveitemsselected.*@return{Card}*/functiononDriveItemsSelected(e){varbuilder=CardService.newCardBuilder();//ForeachitemtheuserhasselectedinDrive,displayeitherits//quotainformationorabuttonthatallowstheusertoprovide//permissiontoaccessthatfiletoretrieveitsquotadetails.e['drive']['selectedItems'].forEach(function(item){varcardSection=CardService.newCardSection().setHeader(item['title']);//Thisadd-onusestherecommended,limited-permission`drive.file`//scopetogetgranularper-fileaccesspermissions.//See:https://developers.google.com/drive/api/v2/about-authif(item['addonHasFileScopePermission']){//Iftheadd-onhasaccesspermission,readanddisplayits//quota.cardSection.addWidget(CardService.newTextParagraph().setText("This file takes up: "+getQuotaBytesUsed(item['id'])));}else{//Iftheadd-ondoesnothaveaccesspermission,addabutton//thatallowstheusertoprovidethatpermissiononaper-file//basis.cardSection.addWidget(CardService.newTextParagraph().setText("The add-on needs permission to access this file's quota."));varbuttonAction=CardService.newAction().setFunctionName("onRequestFileScopeButtonClicked").setParameters({id:item.id});varbutton=CardService.newTextButton().setText("Request permission").setOnClickAction(buttonAction);cardSection.addWidget(button);}builder.addSection(cardSection);});returnbuilder.build();}/***Callbackfunctionforabuttonaction.InstructsDrivetodisplaya*permissionsdialogtotheuser,requesting`drive.file`scopefora*specificitemonbehalfofthisadd-on.**@param{Object}eTheparametersobjectthatcontainstheitem's*DriveID.*@return{DriveItemsSelectedActionResponse}*/functiononRequestFileScopeButtonClicked(e){varidToRequest=e.parameters.id;returnCardService.newDriveItemsSelectedActionResponseBuilder().requestFileScope(idToRequest).build();}/***UsetheAdvancedDriveService*(Seehttps://developers.google.com/apps-script/advanced/drive),*with`drive.file`scopepermissionstorequestthequotausageofa*specificDriveitem.**@param{string}itemIdTheIDoftheitemtocheck.*@return{string}Adescriptionoftheitem's quota usage, in bytes.*/functiongetQuotaBytesUsed(itemId){try{returnDrive.Files.get(itemId,{fields:"quotaBytesUsed"}).quotaBytesUsed+" bytes";}catch(e){return"Error fetching how much quota this item uses. Error: "+e;}}
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-08-01 UTC."],[[["\u003cp\u003eActions enable interactive behavior in Google Workspace add-ons, defining responses to user interactions with widgets.\u003c/p\u003e\n"],["\u003cp\u003eDrive add-ons use a specialized DriveItemsSelectedActionResponse to manage file access permissions.\u003c/p\u003e\n"],["\u003cp\u003eAdd-ons need the \u003ccode\u003ehttps://www.googleapis.com/auth/drive.file\u003c/code\u003e scope to request and utilize Drive file access.\u003c/p\u003e\n"],["\u003cp\u003eThe provided example demonstrates building a contextual Drive interface, requesting file access, and displaying quota usage upon permission grant.\u003c/p\u003e\n"]]],["Actions in Google Workspace add-ons define interactive behaviors triggered by widget interactions. Widgets use handler functions to attach actions, executing callback functions upon user interaction. These callbacks receive an event object containing interaction details and must return a specific response. Drive-specific actions allow requesting file access for selected files. The callback, triggered when a user selects a file in drive, checks if access is granted, and, if not, prompts the user for permission using `DriveItemsSelectedActionResponse`. The add-on then displays file quota information if access is granted.\n"],null,["# Drive actions\n\n[`Action`](/workspace/add-ons/concepts/actions) objects let you build interactive\nbehavior into Google Workspace add-ons. They define\nwhat happens when a user interacts with a widget (for example, a button) in\nthe add-on UI.\n\nAn action is attached to a given widget using a\n[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\n[callback function](/workspace/add-ons/concepts/actions#callback_functions).\nThe callback function is passed an\n[event object](/workspace/add-ons/concepts/event-objects) that carries\ninformation about the user's client-side interactions. You must implement the\ncallback function and have it return a specific response object.\n\nFor example, say you want a button that builds and displays a new card when\nclicked. For this, you must create a new button widget and use the button widget\nhandler function\n[`setOnClickAction(action)`](/apps-script/reference/card-service/text-button#setOnClickAction(Action))\nto set a card-building [`Action`](/workspace/add-ons/concepts/actions). The\n[`Action`](/workspace/add-ons/concepts/actions) you define specifies an Apps Script\ncallback function that executes when the button is clicked. In this case, you\nimplement the callback function to build the card you want and return an\n[`ActionResponse`](/apps-script/reference/card-service/action-response)\nobject. The response object tells the add-on to display the card the callback\nfunction built.\n\nThis page describes Drive-specific widget actions you can include in your\nadd-on.\n\nDrive interactions\n------------------\n\nGoogle Workspace add-ons that extend Drive can include\nan additional Drive-specific widget action. This action requires the associated\naction [callback function](/workspace/add-ons/concepts/actions#callback_functions)\nto return a specialized response object:\n\n| Action attempted | Callback function should return |\n|-----------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------|\n| [Request file access for selected files](#request_file_access_for_selected_files) | [`DriveItemsSelectedActionResponse`](/apps-script/reference/card-service/drive-items-selected-action-response) |\n\nTo make use of these widget actions and response objects, all of the following\nmust be true:\n\n- The action is triggered while the user has one or more Drive items selected.\n- The add-on includes the `https://www.googleapis.com/auth/drive.file` [Drive scope](/workspace/add-ons/concepts/workspace-scopes#drive_scopes) in its manifest.\n\n### Request file access for selected files\n\nThe following example shows how to build a contextual interface for Google\nDrive that is triggered when the user selects one or more Drive items. The\nexample tests each item to see if the add-on has been granted access permission;\nif not, it uses a [`DriveItemsSelectedActionResponse`](/apps-script/reference/card-service/drive-items-selected-action-response)\nobject to request that permission from the user. Once permission is granted for\nan item, the add-on displays the Drive quota usage of that item. \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 contextual information about\n * the Drive items selected.\n * @return {Card}\n */\n function onDriveItemsSelected(e) {\n var builder = CardService.newCardBuilder();\n\n // For each item the user has selected in Drive, display either its\n // quota information or a button that allows the user to provide\n // permission to access that file to retrieve its quota details.\n e['drive']['selectedItems'].forEach(\n function(item){\n var cardSection = CardService.newCardSection()\n .setHeader(item['title']);\n\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 (item['addonHasFileScopePermission']) {\n // If the add-on has access permission, read and display its\n // quota.\n cardSection.addWidget(\n CardService.newTextParagraph().setText(\n \"This file takes up: \" + getQuotaBytesUsed(item['id'])));\n } else {\n // If the add-on does not have access permission, add a button\n // that allows the user to provide that permission on a per-file\n // 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 .setParameters({id: item.id});\n\n var button = CardService.newTextButton()\n .setText(\"Request permission\")\n .setOnClickAction(buttonAction);\n\n cardSection.addWidget(button);\n }\n\n builder.addSection(cardSection);\n });\n\n return builder.build();\n }\n\n /**\n * Callback function for a button action. Instructs Drive to display a\n * permissions dialog to the user, requesting `drive.file` scope for a\n * specific item on behalf of this add-on.\n *\n * @param {Object} e The parameters object that contains the item's\n * Drive ID.\n * @return {DriveItemsSelectedActionResponse}\n */\n function onRequestFileScopeButtonClicked (e) {\n var idToRequest = e.parameters.id;\n return CardService.newDriveItemsSelectedActionResponseBuilder()\n .requestFileScope(idToRequest).build();\n }\n\n /**\n * Use the Advanced Drive Service\n * (See https://developers.google.com/apps-script/advanced/drive),\n * with `drive.file` scope permissions to request the quota usage of a\n * specific Drive item.\n *\n * @param {string} itemId The ID of the item to check.\n * @return {string} A description of the item's quota usage, in bytes.\n */\n function getQuotaBytesUsed(itemId) {\n try {\n return Drive.Files.get(itemId,{fields: \"quotaBytesUsed\"})\n .quotaBytesUsed + \" bytes\";\n } catch (e) {\n return \"Error fetching how much quota this item uses. Error: \" + e;\n }\n }"]]