首页 > 解决方案 > 通过调用 Web 应用程序解锁 Google 电子表格

问题描述

我正在使用 Google 表格构建销售电子表格,我需要用户可以通过单击“编辑”按钮解锁特定范围的单元格,以便他们可以编辑现有的销售。问题是用户没有更改受保护单元格的授权,因此脚本在他们运行时无法解锁单元格。因此,我需要任何用户都能够以我(作者)身份解除对运行脚本的工作表的保护。

我尝试了两天的解决方案是将脚本部署为解锁单元的 Web 应用程序,以我的身份执行,并从另一个脚本访问其 URL,因此用户将使用我的凭据间接解锁单元。我做了什么:

  1. 使用解锁单元格的代码创建了一个 doPost 函数:

function doPost() {
  var app = SpreadsheetApp;
  var ss = app.openByUrl('https://docs.google.com/spreadsheets/d/[SPREADSHEET_ID]');
  var activeSheet = ss.getSheetByName('Create-Edit Sales');
  
  //change cells' color to white
  activeSheet.getRange('A5:B5').setBackground('#ffffff');
  
  //remove cells' protection
  var allProtections = activeSheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var matchingProtections = allProtections.filter(function(existingProtection) {
  return existingProtection.getRange().getA1Notation() == 'A5:B5';
  });
  var protection = matchingProtections[0];
  protection.remove();
}

  1. 将上述脚本部署为 Web 应用程序,它给了我一个https://script.google.com/macros/s/[WEB_APP]/exec URL。

  2. 最后,我创建了一个函数,当用户按下“编辑”按钮时会触发该函数。然后此函数将使用其 URL 和我的项目凭据调用 Web 应用程序:

function UnlockCells(form) {
  var CLIENT_ID = 'CLIENT_ID.apps.googleusercontent.com';
  var CLIENT_SECRET = 'CLIENT_SECRET';
  var url = "https://script.google.com/macros/s/[WEB_APP]/exec";
  
  var options = {  
    headers: {"Authorization": "Basic " + Utilities.base64Encode(CLIENT_ID + ':' + CLIENT_SECRET)},
    method: "post",
    payload: form, //don't know what to use in payload
  }
  
  var response = UrlFetchApp.fetch(url, options);
  Logger.log('responseCode: ' + response);//View the Logs
}

当我运行 UnlockCells 函数时,我收到以下消息:

Request failed for https://script.google.com/macros/s/[WEB_APP]/exec returned code 401. Truncated server response: <!DOCTYPE html><html lang="en"><head><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" c... (use muteHttpExceptions option to examine full response) (line 461, file "Sales Scripts")

对于我在网络上搜索的内容,此错误 401 与身份验证问题有关,但我查看了所有 OAuth 和 API 的配置,但找不到问题。

**注意:如果我将 doPost 函数更改为 doGet 并从任何浏览器访问 Web 应用程序 URL,doGet 函数中的脚本将正确执行,并且工作表中的单元格被解锁。

我在正确的方向吗?这样做的最佳方法是什么?

最好的问候,谢谢!

标签: javascriptgoogle-apps-scriptweb-applicationsgoogle-sheetshttp-status-code-401

解决方案


推荐阅读