大部分的外掛程式除了顯示資料外,也會要求使用者輸入資訊。當您建構卡片式外掛程式時,您可以使用互動式小工具 (例如按鈕、工具列選單項目或核取方塊),要求使用者提供外掛程式需要的資料,或提供其他互動控制項。
將動作新增至小工具
大致上,如要讓小工具進行互動,請將小工具連結至特定「動作」,並在回呼函式中實作必要的行為。詳情請參閱外掛程式動作。
在大多數情況下,您可以按照以下一般程序,將小工具設為在選取或更新時執行特定動作:
範例
以下範例會設定按鈕,在使用者點選後顯示使用者通知。點擊會觸發 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
列舉指定開啟和關閉行為。讓回呼函式保持簡單。為了讓外掛程式保持回應速度,資訊卡服務將回呼函式的執行時間限制為 30 秒。如果執行時間過長,外掛程式 UI 可能不會根據
Action
正確更新資訊卡顯示方式。如果第三方後端的資料狀態因使用者與外掛程式 UI 互動而改變,建議外掛程式將「狀態已變更」位元設為
true
,以便清除現有的用戶端快取。詳情請參閱ActionResponseBuilder.setStateChanged()
方法說明。