You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gmail插件中Session.getActiveUserLocale在iOS端无返回值问题

Gmail插件中Session.getActiveUserLocale()在iOS端返回空值的解决方法

你在开发Gmail插件时遇到的问题是:Session.getActiveUserLocale()在桌面浏览器Gmail环境中能正常获取用户语言(如fr),但在iOS版Gmail应用中返回空值。这是由于移动端Gmail插件的运行上下文与浏览器环境存在差异,导致该API无法正常读取区域设置信息。

以下是几个可行的替代解决方案:

方案1:通过插件事件上下文获取语言

Gmail插件的触发事件(比如打开侧边栏、卡片动作)会传递包含用户语言信息的上下文对象,这个字段在移动端环境中是可靠的。示例代码:

function onGmailSidebarOpen(e) {
  // 优先从事件上下文获取用户语言,为空则设默认值
  const userLocale = e.userLocale || 'en';
  const userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('USER_LANGUAGE', userLocale);
  Logger.log('User locale: ' + userLocale);
  return userLocale;
}

方案2:从用户Google账户提取区域信息

如果事件上下文未提供语言字段,可以借助People API获取用户账户的区域设置(需提前启用API并配置权限)。示例代码:

function getUserLocaleFromAccount() {
  try {
    const userProfile = People.People.get('people/me', {
      personFields: 'locales'
    });
    if (userProfile.locales?.length > 0) {
      const locale = userProfile.locales[0].value;
      PropertiesService.getUserProperties().setProperty('USER_LANGUAGE', locale);
      Logger.log('User locale: ' + locale);
      return locale;
    }
  } catch (err) {
    Logger.log('获取账户区域信息失败: ' + err);
  }
  // 获取失败时返回默认语言
  return 'en';
}

使用该方法需要在项目中添加OAuth权限(在manifest文件的oauthScopes数组中加入):

"oauthScopes": [
  "https://www.googleapis.com/auth/userinfo.profile",
  "https://www.googleapis.com/auth/script.external_request"
]

方案3:添加默认值兜底逻辑

如果以上方法都无法获取语言,可以直接为locale设置默认值,避免空值影响后续功能:

function getUserLanguage() {
  let locale = Session.getActiveUserLocale();
  // 为空时设置默认语言
  if (!locale) {
    locale = 'en';
  }
  PropertiesService.getUserProperties().setProperty('USER_LANGUAGE', locale);
  Logger.log('User locale: ' + locale);
  return locale;
}

内容的提问来源于stack exchange,提问作者hamed elghoul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:22:33