Msgstr "UrlFetchApp.fetch method called in the global scope." Google Apps Script Ediotor Guidelines

I am developing a google spreadsheet add-in in google apps script editor.

As https://developers.google.com/apps-script/add-ons/lifecycle said, sometimes the script works with limited allowed mode, so we won’t write the code required by high privileges (like UrlFetch) in the global scope.

A warning. When the onOpen (e) function is run, the entire script is loaded and any global statements are executed. These instructions are executed in the same authorization mode as onOpen (e) and will fail if the mode prohibits them. This prevents the onOpen (e) function from starting. If your published add-on cannot add menu items, look in the browser JavaScript console to see if an error has been selected, and then look at the script to see if the onOpen (e) function or global service variables are called, t is allowed in AuthMode. NONE

But I found a very strange behavior "called in a global area." I put all my code in a closure and called them, but still got a warning that I am running UrlFetchApp in a global scope.

finally, I found the difference between "running in the global" vs "area is not global, because the first is var g = function () { /* UrlFetchApp here */ } , and the second is function ng() { /* UrlFetchApp here */ ] .

Below is the code that can be run in the Google script editor. If you run testGlobalScope () with Tg (), you will get a warning. As always, when you only run T.ng (), this is normal.

 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() { Tg() // Tg() 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. } 

My question is:

  • why do they have such a difference?
  • If I still want to use a module template such as var T = (function () {} ()), how can I get rid of the "run in global scope" problem?
+5
source share

Source: https://habr.com/ru/post/1243313/


All Articles