大多數外掛程式除了呈現資料外,還需要使用者輸入資訊。建構以資訊卡為基礎的外掛程式時,您可以使用按鈕、工具列選單項目或核取方塊等互動式小工具,要求使用者提供外掛程式所需的資料,或提供其他互動控制項。
在小工具中新增動作
在大多數情況下,您只要將小工具連結至特定動作,並在回呼函式中實作必要行為,就能讓小工具具備互動性。詳情請參閱外掛程式動作。
在大多數情況下,您可以按照這個一般程序設定小工具,在選取或更新時執行特定動作:
範例
以下範例會設定按鈕,在點選後顯示使用者通知。點選後會觸發 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物件,定義要開啟的網址。您也可以使用這個物件,透過OpenAs和OnClose列舉指定開啟和關閉行為。多個小工具可能會使用相同的
Action物件。不過,如果您想為回呼函式提供不同的參數,就必須定義不同的Action物件。請保持回呼函式簡潔扼要。為確保外掛程式的回應速度,Card 服務將回呼函式的執行時間上限設為 30 秒。如果執行時間超過這個長度,外掛程式 UI 可能無法正確更新卡片顯示畫面,以回應
Action。如果使用者與外掛程式 UI 互動,導致第三方後端的資料狀態變更,建議外掛程式將「狀態已變更」位元設為
true,清除所有現有的用戶端快取。詳情請參閱ActionResponseBuilder.setStateChanged()方法說明。