如何自动关闭Google脚本内容服务/HTML服务创建的窗口?

人气:463 发布:2022-10-16 标签: javascript google-apps-script google-sheets google-sheets-api

问题描述

我在Google脚本中有一个doGet(E)函数,它写入电子表格,然后返回一条用Content Service创建的简单的"Success"消息。我的问题是,有没有办法自动关闭此消息创建的选项卡/窗口?用户在写入电子表格时将"批准"不同的项目,如果使用此函数连续批准多个项目,然后必须关闭该函数创建的每个后续选项卡,则可能会很烦人。

以下是GS:

function doGet(e) {  
  var id = e.parameter.id;
  var fundnumber = e.parameter.fundnumber;
  var date = Utilities.formatDate(new Date(), "America/New_York", "MM/dd/yyyy");

  var sh = SpreadsheetApp.openById("12jWGJWHCLoiLVoA0TlBQ0QgOMxBU9gVj9HQQveiNg0w").getSheetByName("Purchase Order Meta");
  var data = sh.getDataRange().getValues();

  for(n=0;n<data.length;++n){
    if( data[n][1].toString().match(id)==id ){ 
      data[n][8] = 'Approved by Linda on ' + date;
      data[n][16] = 'Approved by Linda on ' + date + '. Awaiting order from Trish.';
      data[n][13] = fundnumber
    }; 
    sh.getRange(1,1,data.length,data[0].length).setValues(data); // write back to the sheet
  }

  return ContentService.createTextOutput("success");
}

我的理解是,为了编写doGet,我必须使用Content Service或HTML Service返回一些内容。我尝试过使用HTMLService并将JS添加到页面以关闭窗口,但似乎不起作用。:

推荐答案

使用HTMLService输出,您可以通过将google.script.host.close()包装在超时函数中来关闭弹出窗口或Html页面,如下所示:

setTimeout( function() { google.script.host.close(); }, 3000);

将您的退货更改为:

var output = "<body><p>Success!</p><script>setTimeout( function() { google.script.host.close(); }, 3000);</script></body>"

return HtmlService.createHtmlOutput(output);

627