大多数插件除了呈现数据之外,还需要用户输入信息。构建基于卡片的插件时,您可以使用按钮、工具栏菜单项或复选框等交互式 widget,向用户索要插件所需的数据,或提供其他互动控件。
向 widget 添加操作
在大多数情况下,您可以通过将 widget 与特定操作相关联并在回调函数中实现所需的行为使 widget 具有可交互性。如需了解详情,请参阅附加操作。
在大多数情况下,您可以按照以下一般流程配置 widget,使其在选定或更新后执行特定操作:
- 创建一个
Action
对象,指定应执行的回调函数以及所有必需的参数。 - 通过调用相应的 widget 处理程序函数将 widget 链接到
Action
。 - 实现回调函数以执行所需的行为。
示例
以下示例会设置一个按钮,点击该按钮后会显示用户通知。点击会触发 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!
}
设计有效互动
在设计互动卡片时,请注意以下几点:
交互式 widget 通常需要至少一个处理程序方法来定义其行为。
如果您有一个网址,只是想在标签页中打开该网址,可以使用
setOpenLink()
widget 处理程序函数。这样就无需定义Action
对象和回调函数。如果您需要先构建网址,或者在打开网址之前需要执行任何其他步骤,请定义Action
并改用setOnClickOpenLinkAction()
。使用
setOpenLink()
或setOnClickOpenLinkAction()
widget 处理程序函数时,您需要提供一个OpenLink
对象来定义要打开的网址。您还可以使用此对象通过OpenAs
和OnClose
枚举指定打开和关闭行为。多个 widget 可以使用同一
Action
对象。不过,如果您希望为回调函数提供不同的参数,则需要定义不同的Action
对象。确保回调函数简单。为了确保插件能及时响应,卡片服务将回调函数的执行时间限制为不超过 30 秒。如果执行时间过长,插件界面可能无法正确更新其卡片显示状态以响应
Action
。如果第三方后端的数据状态因用户与插件界面的互动而发生变化,建议该插件将“状态已更改”位设置为
true
,以便清除任何现有的客户端缓存。如需了解详情,请参阅ActionResponseBuilder.setStateChanged()
方法说明。