建立互動式資訊卡

大部分的外掛程式除了呈現資料之外,還會要求使用者輸入資訊。建構卡片式外掛程式時,您可以使用互動式小工具 (例如按鈕、工具列選單項目或核取方塊),要求使用者提供外掛程式所需的資料,或提供其他互動控制項。

將動作新增至小工具

大部分情況下,您可以將小工具連結至特定「動作」,並在回呼函式中實作必要行為,讓小工具更具互動性。詳情請參閱「外掛程式動作」。

在大部分情況下,您可以按照下列一般程序設定小工具,在選取或更新時採取特定動作:

  1. 建立 Action 物件,指定應執行的回呼函式,以及所有必要參數。
  2. 呼叫適當的小工具處理常式函式,將小工具連結至 Action
  3. 實作回呼函式,以便執行必要行為。

範例

下列範例會設定在點選使用者通知後顯示使用者通知的按鈕。點擊會使用指定通知文字的引數觸發 notifyUser() 回呼函式。傳回建構的 ActionResponse 會產生顯示的通知。

  /**
   * Build a simple card with a button that sends a notification.
   * @return {Card}
   */
  function buildSimpleCard() {
    var buttonAction = CardService.newAction()
        .setFunctionName('notifyUser')
        .setParameters({'notifyText': 'Button clicked!'});
    var button = CardService.newTextButton()
        .setText('Notify')
        .setOnClickAction(buttonAction);

    // ...continue creating widgets, then create a Card object
    // to add them to. Return the built Card object.
  }

  /**
   * Callback function for a button action. Constructs a
   * notification action response and returns it.
   * @param {Object} e the action event object
   * @return {ActionResponse}
   */
  function notifyUser(e) {
    var parameters = e.parameters;
    var notificationText = parameters['notifyText'];
    return CardService.newActionResponseBuilder()
        .setNotification(CardService.newNotification())
            .setText(notificationText)
        .build();      // Don't forget to build the response!
  }

設計有效的互動方式

設計互動式資訊卡時,請注意下列事項:

  • 互動式小工具通常需要至少一個處理常式方法才能定義行為。

  • 如有網址,只想在新分頁中開啟網址,請使用 setOpenLink() 小工具處理常式函式。這樣一來,就不必定義 Action 物件和回呼函式。如果您需要先建構網址,或是在開啟網址前採取其他任何步驟,請定義 Action 並改用 setOnClickOpenLinkAction()

  • 使用 setOpenLink()setOnClickOpenLinkAction() 小工具處理常式函式時,您必須提供 OpenLink 物件以定義要開啟的網址。您也可以使用這個物件,使用 OpenAsOnClose 列舉來指定開始和結束的行為。

  • 多個小工具可能會使用相同的 Action 物件。不過,如要提供回呼函式不同的參數,您必須定義不同的 Action 物件。

  • 保持回呼函式簡單明瞭。為了讓外掛程式保持回應,資訊卡服務會將回呼函式限制執行時間最長為 30 秒。如果執行時間超過此時間,外掛程式 UI 可能無法正確更新資訊卡顯示方式,以回應 Action

  • 如果因為使用者與外掛程式 UI 互動而第三方後端的資料狀態變更,建議您將外掛程式集的「狀態已變更」位元設為 true,才能清除任何現有的用戶端快取。詳情請參閱 ActionResponseBuilder.setStateChanged() 方法說明。