大多数插件除了显示数据外,还需要用户输入信息。构建基于卡片的插件时,您可以使用交互式微件(例如按钮、工具栏菜单项或复选框)来向用户请求插件所需的数据,或提供其他互动控件。
向 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()方法说明。