대부분의 부가기능은 데이터를 표시하는 것 외에도 사용자가 정보를 입력해야 합니다. 카드 기반 부가기능을 빌드할 때 버튼, 툴바 메뉴 항목, 체크박스와 같은 대화형 위젯을 사용하여 사용자에게 부가기능에 필요한 데이터를 요청하거나 다른 상호작용 컨트롤을 제공할 수 있습니다.
위젯에 작업 추가
대부분의 경우 위젯을 특정 작업에 연결하고 콜백 함수에서 필요한 동작을 구현하여 위젯을 대화형으로 만듭니다. 자세한 내용은 부가기능 작업을 참고하세요.
대부분의 경우 다음과 같은 일반적인 절차에 따라 선택 또는 업데이트 시 특정 작업을 실행하도록 위젯을 구성할 수 있습니다.
다음 예에서는 클릭 시 사용자 알림을 표시하는 버튼을 설정합니다. 클릭하면 알림 텍스트를 지정하는 인수와 함께 notifyUser() 콜백 함수가 트리거됩니다. 빌드된 ActionResponse를 반환하면 알림이 표시됩니다.
/***Buildasimplecardwithabuttonthatsendsanotification.*@return{Card}*/functionbuildSimpleCard(){varbuttonAction=CardService.newAction().setFunctionName('notifyUser').setParameters({'notifyText':'Button clicked!'});varbutton=CardService.newTextButton().setText('Notify').setOnClickAction(buttonAction);//...continuecreatingwidgets,thencreateaCardobject//toaddthemto.ReturnthebuiltCardobject.}/***Callbackfunctionforabuttonaction.Constructsa*notificationactionresponseandreturnsit.*@param{Object}etheactioneventobject*@return{ActionResponse}*/functionnotifyUser(e){varparameters=e.parameters;varnotificationText=parameters['notifyText'];returnCardService.newActionResponseBuilder().setNotification(CardService.newNotification().setText(notificationText)).build();//Don't forget to build the response!}
두 개 이상의 위젯에서 동일한 Action 객체를 사용할 수 있습니다.
그러나 콜백 함수에 다른 매개변수를 제공하려면 다른 Action 객체를 정의해야 합니다.
콜백 함수를 간단하게 유지합니다. 부가기능의 응답성을 유지하기 위해 카드 서비스는 콜백 함수를 최대 30초의 실행 시간으로 제한합니다. 실행 시간이 이보다 오래 걸리면 부가기능 UI가 Action에 응답하여 카드 디스플레이를 제대로 업데이트하지 못할 수 있습니다 .
사용자가 부가기능 UI와 상호작용한 결과 서드 파티 백엔드의 데이터 상태가 변경되는 경우 부가기능에서 '상태 변경' 비트를 true로 설정하여 기존 클라이언트 측 캐시가 삭제되도록 하는 것이 좋습니다. 자세한 내용은 ActionResponseBuilder.setStateChanged() 메서드 설명을 참고하세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2024-12-22(UTC)"],[[["\u003cp\u003eCard-based add-ons use interactive widgets like buttons and menus to collect user input and enhance user interactions.\u003c/p\u003e\n"],["\u003cp\u003eWidgets are made interactive by linking them to actions, which trigger callback functions to execute specific behaviors when interacted with.\u003c/p\u003e\n"],["\u003cp\u003eWhen defining widget actions, you can specify a callback function and any necessary parameters using the \u003ccode\u003eAction\u003c/code\u003e object and appropriate handler functions.\u003c/p\u003e\n"],["\u003cp\u003eFor opening URLs, \u003ccode\u003esetOpenLink()\u003c/code\u003e or \u003ccode\u003esetOnClickOpenLinkAction()\u003c/code\u003e can be used with an \u003ccode\u003eOpenLink\u003c/code\u003e object to define the URL and behavior.\u003c/p\u003e\n"],["\u003cp\u003eKeep callback functions concise, as they have execution time limits, and consider using \u003ccode\u003esetStateChanged()\u003c/code\u003e to update the UI when backend data changes due to user interactions.\u003c/p\u003e\n"]]],["Card-based add-ons use interactive widgets like buttons to gather user input or provide controls. Widgets are made interactive by linking them to actions via a callback function. To configure a widget, create an `Action` object with the callback function and parameters, link it using a widget handler function, and implement the callback function. For opening URLs directly, `setOpenLink()` avoids defining an `Action`. Ensure callbacks are simple (under 30 seconds), and for backend data changes, use `setStateChanged()`.\n"],null,["# Building interactive cards\n\nMost add-ons, in addition to presenting data, require the user to enter\ninformation. When you build a card-based add-on, you can use\ninteractive [widgets](/workspace/add-ons/concepts/widgets) such as buttons,\ntoolbar menu items, or checkboxes to ask the user for data that your add-on\nneeds or provide other interaction controls.\n\nAdding actions to widgets\n-------------------------\n\nFor the most part, you make widgets interactive by linking them to\nspecific *actions* and implementing the required behavior in a callback\nfunction. See [add-on actions](/workspace/add-ons/concepts/actions) for details.\n\nIn most cases, you can follow this general procedure to configure a widget to\ntake a specific action when selected or updated:\n\n1. Create an [`Action`](/apps-script/reference/card-service/action) object, specifing the callback function that should execute, along with any required parameters.\n2. Link the widget to the `Action` by calling the appropriate [widget handler function](/workspace/add-ons/concepts/actions#widget_handler_functions).\n3. Implement the [callback function](/workspace/add-ons/concepts/actions#callback_functions) to enact the required behavior.\n\nExample\n-------\n\nThe following example sets a button that displays a user notification\nafter it is clicked. The click triggers the `notifyUser()` callback function\nwith an argument that specifies the notification text. Returning a built\n[`ActionResponse`](/apps-script/reference/card-service/action-response)\nresults in a displayed notification. \n\n /**\n * Build a simple card with a button that sends a notification.\n * @return {Card}\n */\n function buildSimpleCard() {\n var buttonAction = CardService.newAction()\n .setFunctionName('notifyUser')\n .setParameters({'notifyText': 'Button clicked!'});\n var button = CardService.newTextButton()\n .setText('Notify')\n .setOnClickAction(buttonAction);\n\n // ...continue creating widgets, then create a Card object\n // to add them to. Return the built Card object.\n }\n\n /**\n * Callback function for a button action. Constructs a\n * notification action response and returns it.\n * @param {Object} e the action event object\n * @return {ActionResponse}\n */\n function notifyUser(e) {\n var parameters = e.parameters;\n var notificationText = parameters['notifyText'];\n return CardService.newActionResponseBuilder()\n .setNotification(CardService.newNotification()\n .setText(notificationText))\n .build(); // Don't forget to build the response!\n }\n\nDesign effective interactions\n-----------------------------\n\nWhen designing interactive cards, keep the following in mind:\n\n- Interactive widgets usually need at least one handler method to define their\n behavior.\n\n- Use the [`setOpenLink()`](/workspace/add-ons/concepts/actions#setOpenLink) widget\n handler function when you have a URL and just want to open it in a tab.\n This avoids the need to define an\n [`Action`](/apps-script/reference/card-service/action) object and callback\n function. If you need to build the URL first, or take any other additional\n steps before opening the URL, define an\n [`Action`](/apps-script/reference/card-service/action) and use\n [`setOnClickOpenLinkAction()`](/workspace/add-ons/concepts/actions#setOnClickOpenLinkAction)\n instead.\n\n- When using the [`setOpenLink()`](/workspace/add-ons/concepts/actions#setOpenLink)\n or [`setOnClickOpenLinkAction()`](/workspace/add-ons/concepts/actions#setOnClickOpenLinkAction)\n widget handler functions, you need to provide an\n [`OpenLink`](/apps-script/reference/card-service/open-link)\n object to define which URL to open. You can also use this object\n to specify opening and closing behavior using the\n [`OpenAs`](/apps-script/reference/card-service/open-as) and\n [`OnClose`](/apps-script/reference/card-service/on-close) enums.\n\n- It is possible for more than one widget to use the same\n [`Action`](/apps-script/reference/card-service/action) object.\n However, you need to define different\n [`Action`](/apps-script/reference/card-service/action) objects if you want\n to provide the callback function different parameters.\n\n- Keep your callback functions simple. To keep the add-ons responsive, the\n [Card service](/apps-script/reference/card-service/card-service) limits callback functions to a maximum of 30 seconds of\n execution time. If the execution takes longer than that, your add-on UI may\n not update its card display properly in response to the\n [`Action`](/apps-script/reference/card-service/action) .\n\n- If a data status on a third-party backend changes as the result of a user\n interaction with your add-on UI, it is recommended that the add-on set\n a 'state changed' bit to `true` so that any existing client side cache is\n cleared. See the\n [`ActionResponseBuilder.setStateChanged()`](/apps-script/reference/card-service/action-response-builder#setStateChanged(Boolean))\n method description for additional details."]]