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

如何通过Google Apps Script获取用户的ChromeOS及Chrome浏览器版本?

解决方案

1. 前端直接获取Chrome浏览器版本

Chrome浏览器版本属于客户端环境信息,无需通过后端API调用,直接在WebApp的前端页面用JavaScript即可获取,这是最高效的方式:

<!-- index.html -->
<!DOCTYPE html>
<html>
  <body>
    <script>
      // 提取完整Chrome版本号
      const chromeVersionMatch = navigator.userAgent.match(/Chrome\/(\d+\.\d+\.\d+\.\d+)/);
      const chromeVersion = chromeVersionMatch ? chromeVersionMatch[1] : "无法检测";
      
      // 将浏览器版本传给后端,同时请求ChromeOS版本
      google.script.run.withSuccessHandler(showResults)
          .fetchChromeOSInfo(chromeVersion);
      
      function showResults(info) {
        document.body.innerHTML = `
          <h3>设备信息</h3>
          <p>Chrome浏览器版本: ${info.chromeVersion}</p>
          <p>ChromeOS版本: ${info.chromeOSVersion || "未找到关联的Chromebook设备"}</p>
        `;
      }
    </script>
  </body>
</html>

2. 优化ChromeOS版本获取逻辑

你之前遍历所有设备再匹配用户的方法效率极低,还容易出错。可以利用AdminDirectory.Chromeosdevices.list的query参数,直接筛选出与当前用户关联的设备,大幅减少API调用次数:

// Code.gs
function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');
}

function fetchChromeOSInfo(chromeVersion) {
  const userEmail = Session.getActiveUser().getEmail();
  const customerId = 'my_customer'; // 若不确定,可通过AdminDirectory.Users.get(userEmail).customerId动态获取
  
  // 核心优化:用query参数直接过滤出最近使用用户包含当前用户的设备
  const listParams = {
    query: `recentUsers.email:${userEmail}`,
    maxResults: 1, // 优先取用户最近使用的设备
    projection: 'BASIC' // 只获取必要字段,减少数据传输量
  };

  const deviceResponse = AdminDirectory.Chromeosdevices.list(customerId, listParams);
  const targetDevice = deviceResponse.chromeosdevices?.[0];
  const chromeOSVersion = targetDevice?.osVersion;

  return {
    chromeVersion: chromeVersion,
    chromeOSVersion: chromeOSVersion
  };
}

关键注意事项

  • 权限配置:必须在Google Cloud Console中启用Admin Directory API,且WebApp的部署者需要拥有域管理员权限;部署时可选择"以访问该应用的用户身份执行"(需用户授权)或"以我(部署者)的身份执行"(适合管理员统一查询)。
  • 修复原有代码bug:你之前的代码中usrDev[2]是错误的,存入数组的是[device.deviceId, device.recentUsers[0].email],用户邮箱的索引应为1而非2。
  • 多设备处理:如果用户有多个Chromebook设备,可以去掉maxResults:1,遍历返回的设备列表,展示所有关联设备的版本信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:45:27