JavaScript检测代码是否运行在Google App Script环境的惯用方法是什么
Google Apps Script 环境检测惯用方案
服务端运行时检测(最常用)
优先检测GAS专属的核心全局对象ScriptApp,该对象仅在GAS服务端环境存在,命名特殊性极高,几乎不会和普通JavaScript项目的自定义变量冲突,检测代码如下:
const isGoogleAppsScript = typeof ScriptApp !== 'undefined' && typeof ScriptApp.getService === 'function'
如果需要进一步降低极端场景下的误判概率,可以叠加另一个GAS专属的全局对象Utilities做双重校验:
const isGoogleAppsScript = typeof ScriptApp !== 'undefined' && typeof Utilities !== 'undefined' && typeof Utilities.newBlob === 'function'
HtmlService前端页面环境检测
如果需要检测的是通过GAS的HtmlService渲染的前端页面环境,可检测GAS专属的前端API对象:
const isGasHtmlPage = typeof google !== 'undefined' && typeof google.script !== 'undefined' && typeof google.script.run !== 'undefined'
方案说明
你之前考虑的Logger、Menu、Ui这类对象确实通用性较强,容易和业务代码的自定义变量重名,不推荐作为检测依据。上述方案是目前GAS开发者社区普遍使用的惯用检测方案,暂未出现官方推荐的标准检测逻辑,该方案的误判概率可以忽略。
内容的提问来源于stack exchange,提问作者Chris Adams
相关产品推荐
相关产品推荐

