getFileAccess(fileId) returns the access the script's effective user has on a Drive file or folder: 'edit', 'comment', 'view', or 'none'. Check this before a write so a "you do not have permission" failure is easier to tell from a missing OAuth scope or a simple-trigger limit.
When to use
- Guarding a write to a file someone else owns
- Logging whether the user who ran the script can edit, comment, or only view
- Narrowing down a permission error before you change scopes or sharing
How to use this snippet
/**
* Access level of the effective user on a Drive file (or folder).
* Returns 'edit' (including owner / organizer), 'comment', 'view', or 'none'.
* Missing files, shared-drive items DriveApp cannot read, and getAccess
* failures all return 'none' — this does not distinguish "no such file"
* from "no access."
*
* @param {string} fileId
* @return {'edit'|'comment'|'view'|'none'}
*/
function getFileAccess(fileId) {
var item = null;
try {
item = DriveApp.getFileById(fileId);
} catch (e) {
try {
item = DriveApp.getFolderById(fileId);
} catch (e2) {
return 'none';
}
}
try {
var access = item.getAccess(Session.getEffectiveUser());
var s = String(access);
if (s === 'AUTH_PENDING') return 'none';
if (/OWNER|ORGANIZER|EDIT/i.test(s)) return 'edit';
if (/COMMENT/i.test(s)) return 'comment';
if (/VIEW/i.test(s)) return 'view';
return 'none';
} catch (e) {
return 'none';
}
}
Example
function canEditBeforeWrite(fileId) {
var access = getFileAccess(fileId);
if (access !== 'edit') {
throw new Error('Need edit access to ' + fileId + ' (have ' + access + ')');
}
}
Notes
- The user is
Session.getEffectiveUser()— the owner of an installable trigger, or the account that authorized the script, not always the person who opened the spreadsheet. A simple trigger often has no effective email and cannot call DriveApp at all. - Owner, organizer, and file-organizer map to
'edit'because those roles can write.'none'covers both "no access" and "DriveApp could not see the file." - This is the current user's access, not a list of every editor. For that, see List Folder Sharing.
- DriveApp still cannot read some shared-drive items; those also come back as
'none'.
Happy Coding!
