You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Google Web应用中表格权限授权及用户信息调用的失效问题

解决授权按钮失效问题的具体方案

一、修复后端reauthorize函数

原函数在未授权状态下调用ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL)会报错,因为当前运行环境的授权模式并非FULL。修改为以下逻辑,先检测授权状态,再生成对应URL:

function reauthorize() {
  try {
    // 尝试执行需要授权的操作,验证是否已授权
    AdminDirectory.Users.get(Session.getActiveUser().getEmail(), {viewType:'domain_public'});
    return "已完成授权";
  } catch (e) {
    // 未授权时,获取公开模式下的授权URL
    const authUrl = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.NONE).getAuthorizationUrl();
    return authUrl;
  }
}

二、完善前端错误处理

原前端代码缺少错误回调,无法定位调用失败原因。添加错误处理逻辑,同时区分返回结果类型:

<button id="reauth">Reauthorize</button>
<script>
  $('#reauth').click(function() {
    google.script.run
      .withSuccessHandler(function(response) {
        if (response.startsWith("https://")) {
          window.open(response, '_blank');
        } else {
          alert(response);
        }
      })
      .withFailureHandler(function(error) {
        alert("授权请求失败: " + error.message);
      })
      .reauthorize();
  });
</script>

三、检查Web应用部署配置

确保部署时的权限设置正确:

  • 执行权限:选择「用户访问Web应用时」(使用访问者自身的账号权限)
  • 访问权限:根据组织需求选择(如「组织内的任何人」)
  • 修改代码后必须重新部署新版本,否则配置不会生效

四、启用Admin Directory服务

在脚本编辑器中,点击「服务」→「添加服务」,找到并启用「Admin Directory」,否则无法调用AdminDirectory.Users.get方法。

五、优化库存更新函数的容错性

避免未授权时整个流程崩溃,同时修复日志覆盖问题:

function updateData(row, column, newData, userEmail, item) {
  // 更新库存状态
  const cell = inventorySheet.getRange(row, column);
  cell.setValue(newData);

  // 获取用户名(未授权时用邮箱替代)
  let userName;
  try {
    const user = AdminDirectory.Users.get(userEmail, {viewType:'domain_public'});
    userName = user.name.fullName;
  } catch (e) {
    userName = userEmail;
  }

  // 写入日志(改为追加到新行,避免覆盖旧日志)
  const [date, time] = dateTime();
  const logNote = `${userName} checked ${item} back in at ${time} hours on ${date}`;
  const nextRow = logSheet.getLastRow() + 1;
  logSheet.getRange(nextRow, 1).setValue(logNote);
}

内容的提问来源于stack exchange,提问作者Borgher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:13:13