首页 > 解决方案 > onclick 动作完成执行后返回

问题描述

我有一个脚本来检查是否设置了用户属性。如果不是,则显示设置菜单,如果是,则显示设置按钮。问题是当我提交设置(通过设置新设置或更改旧设置)时,我无法使脚本返回主菜单,即重新运行MainFunction. 有人可以帮我吗?

function MainFunction() {
  var userProperties = PropertiesService.getUserProperties();
  var api_key = userProperties.getProperty('api_key');
  var source = userProperties.getProperty('source');
  console.log(api_key);
  console.log(source);
  if (api_key == null || source == null || api_key.length < 2 || source.length < 2) {
    return f_change_settings();
  } else {
    return f_add_settings_button();
  }
}

function f_change_settings(s) {  
  var userProperties = PropertiesService.getUserProperties();
  var api_key = userProperties.getProperty('api_key');
  var source = userProperties.getProperty('source');

  var action = CardService.newAction().setFunctionName('notificationCallback');
  return CardService
  .newCardBuilder()
  .addSection(
    CardService.newCardSection()
    .addWidget(CardService.newTextInput().setFieldName('api_key').setTitle('api_key').setValue(api_key))
    .addWidget(CardService.newTextInput().setFieldName('source').setTitle('source').setValue(api_key))
    .addWidget(CardService.newTextButton().setText('Submit').setOnClickAction(action))
    .addWidget(CardService.newTextParagraph().setText(' '))
  )
  .build();
}

function notificationCallback(a) {
  console.log(a);
  console.log(a.formInput['source']);
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('api_key', a.formInput['api_key']);
  userProperties.setProperty('source', a.formInput['source']);
  CardService.newActionResponseBuilder()
  .setNotification(CardService.newNotification()
  .setText("Done"))
  .build();
//  MainFunction();
  return;
}

function f_add_settings_button() {  
  var action = CardService.newAction().setFunctionName('f_change_settings');
  return CardService
  .newCardBuilder()
  .addSection(
    CardService.newCardSection()
    .addWidget(CardService.newTextButton().setText('Settings').setOnClickAction(action))
    .addWidget(CardService.newTextParagraph().setText(' '))
  )
  .build();
}

我尝试MainFunction从回调中调用但不工作(注释行)。

标签: google-apps-script

解决方案


您可以设置MainFunction为您的回调,而不是notificationCallback

var action = CardService.newAction().setFunctionName('MainFunction');

并在此函数的开头设置新的用户属性(仅当之前有表单提交时):

function MainFunction(a) {
  var userProperties = PropertiesService.getUserProperties();
  if (a.formInput['api_key'] && a.formInput['source']) {
    userProperties.setProperty('api_key', a.formInput['api_key']);
    userProperties.setProperty('source', a.formInput['source']);
  }
  var api_key = userProperties.getProperty('api_key');
  var source = userProperties.getProperty('source');
  if (api_key == null || source == null || api_key.length < 2 || source.length < 2) {
    return f_change_settings();
  } else {
    return f_add_settings_button();
  }
}

推荐阅读