如何在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获取当前用户的最近访问文件夹(大概率是当前视图的文件夹):
- 脚本编辑器中点击「资源」→「高级Google服务」,启用Drive API
- 服务器端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
相关产品推荐
相关产品推荐

