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

如何在Google Apps Script中获取Drive当前文件夹ID(无文件选中/打开时)

获取Google Drive当前文件夹ID(无选中文件/未打开文档场景)

方法1:侧边栏客户端脚本提取URL中的ID

如果插件使用侧边栏,可通过客户端JS提取URL里的文件夹ID,再传给服务器端:

  • 客户端HTML代码:
<script>
  const url = window.location.href;
  const folderId = url.match(/folders\/([a-zA-Z0-9-_]+)/)?.[1];
  if (folderId) {
    google.script.run.processFolderId(folderId);
  }
</script>
  • 服务器端GS代码:
function processFolderId(folderId) {
  const folder = DriveApp.getFolderById(folderId);
  // 后续逻辑,比如操作文件夹
  console.log(`当前文件夹:${folder.getName()}(ID:${folderId})`);
}

方法2:调用Drive API获取当前视图文件夹

若无法使用侧边栏,启用高级Drive服务后,通过API获取当前用户的最近访问文件夹(大概率是当前视图的文件夹):

  1. 脚本编辑器中点击「资源」→「高级Google服务」,启用Drive API
  2. 服务器端GS代码:
function getCurrentFolderId() {
  const token = ScriptApp.getOAuthToken();
  const res = UrlFetchApp.fetch(
    "https://www.googleapis.com/drive/v3/files?q=mimeType='application/vnd.google-apps.folder'&orderBy=viewedByMeTime desc&pageSize=1&fields=files(id)",
    { headers: { Authorization: `Bearer ${token}` } }
  );
  const data = JSON.parse(res.getContentText());
  return data.files?.[0]?.id || null;
}

注:使用viewedByMeTime排序可优先获取用户最近查看的文件夹,适配切换后未修改的场景。

方法3:插件上下文触发时获取

在插件的Drive激活事件中,判断无选中文件时调用上述方法:

function onDriveHomepage(e) {
  if (e.drive.selectedFiles.length === 0) {
    const folderId = getCurrentFolderId();
    if (folderId) {
      return CardService.newCardBuilder()
        .addSection(CardService.newCardSection()
          .addWidget(CardService.newTextParagraph().setText(`当前文件夹ID:${folderId}`)))
        .build();
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:45:41