我正在Google Apps脚本编辑器中开发Google电子表格加载项。

正如https://developers.google.com/apps-script/add-ons/lifecycle所说,有时脚本以限制授权模式运行,因此我们不会在全局范围内编写任何需要高特权(例如UrlFetch)的代码。



但是我发现“在全局范围内调用”是一个非常奇怪的行为。我将所有代码放在闭包中,然后调用它们,但仍然收到警告,提示我在全局范围内运行UrlFetchApp。

最后,我发现了“在全局范围内运行”与“在全局范围内运行”之间的区别之所以不是“not global”,是因为第一个是var g = function () { /* UrlFetchApp here */ },第二个是function ng() { /* UrlFetchApp here */ ]

以下代码可以在Google脚本编辑器中运行。如果使用T.g()运行testGlobalScope(),将得到警告。但是,仅在运行T.ng()的时候就可以了。

var T = (function() {
  var g = function () {
    // Method UrlFetchApp.fetch invoked in the global scope.
    try { UrlFetchApp.fetch('http://google.com') } catch (e) {}
  }

  function ng() {
    try { UrlFetchApp.fetch('http://google.com') } catch (e) {}
  }

  return {
    g: g
    , ng: ng
  }

}())

function testGlobalScope() {
  T.g() // T.g() will cause Script Editor show "Execution Hints" with red light: Method UrlFetchApp.fetch invoked in the global scope.
//  T.ng() // This will not show any warning.
}

我的问题是:
  • 为什么会有这种区别?
  • 如果我仍然想使用像var T =(function(){}())这样的模块模式,如何摆脱“在全局范围内运行”的问题?
  • 最佳答案

    这是一个比较老的版本,但是会尝试回答。

    0)尽管该警告确实显示在脚本编辑器中,但即使未向脚本授予任何权限,它似乎也不能阻止onOpen函数的运行。因此,可能没有实际原因就显示了警告。

    0.1)仍然会显示它,并且您声明T的精确程度也无关紧要:无论是function T()var T = function T() { ... }还是var T = (function() { ... }()),都会显示警告。

    1)并不是很清楚,只能基于上面和下面进行假设(也许Execution hints会认为任何匿名函数都属于全局范围?)。

    2)但是,尽管g必须是一个命名函数,但看起来仍然有一种方法可以消除警告,同时仍将函数声明为表达式:

    var T = (function() {
      var g = function g() {
        // No "Method UrlFetchApp.fetch invoked in the global scope." warning
        try { UrlFetchApp.fetch('http://google.com') } catch (e) {}
      }
    
      function ng() {
        try { UrlFetchApp.fetch('http://google.com') } catch (e) {}
      }
    
      return {
        g: g
        , ng: ng
      }
    
    })()
    

    关于google-apps-script - Google Apps脚本编辑器执行提示的"Method UrlFetchApp.fetch invoked in the global scope.",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35479160/

    10-12 12:22
    查看更多