建立互動式資訊卡

大部分的外掛程式除了呈現資料之外,還需要使用者必須自行輸入 可能不準確或不適當建立卡片式外掛程式時,您可以使用 互動小工具,例如按鈕、 工具列選單項目或核取方塊,即可要求使用者提供外掛程式 或提供其他互動控制項

將動作新增至小工具

大部分情況下,只要將小工具連結至 具體動作,並在回呼中實作所需行為 函式。詳情請參閱「外掛程式動作」。

在大部分的情況下,您可以按照這個一般程序將小工具設定為 執行特定操作:

  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 秒內 執行時間。如果執行時間超過 30 秒,外掛程式 UI 可能會 未正確更新卡片顯示,以回應 Action

  • 如果使用者導致第三方後端的資料狀態變更 建議您選用外掛程式集 「狀態已變更」設為 true,這樣現有用戶端快取的所有現有用戶端快取都會 已清除。詳情請參閱 ActionResponseBuilder.setStateChanged() 方法說明。