Sub topic 13
Automating sharing and protection with Apps Script
This chapter assumes you can share a sheet from the Share dialog, know the Viewer, Commenter and Editor roles, and have protected a range by hand. It also assumes basic JavaScript. You will use Apps Script to apply the same sharing and protection changes from code, which is useful when you need to repeat them across many people or many files.
Where scripted sharing fits
Apps Script is Google's JavaScript environment for Workspace. A script bound to a spreadsheet (opened from Extensions > Apps Script) can call two services that matter here:
SpreadsheetAppworks with the spreadsheet itself: its viewers and editors, its sheets, and its protections.DriveAppworks with the spreadsheet as a Drive file: general access (link sharing), the Commenter role, and ownership.
Neither service replaces the other. Some of the controls you know from the Share dialog live on one service only, so you often combine them. The table shows where each action lives.
| Action | Service and method |
|---|---|
| Add a Viewer | `Spreadsheet.addViewer(email)` or `File.addViewer(email)` |
| Add an Editor | `Spreadsheet.addEditor(email)` or `File.addEditor(email)` |
| Add a Commenter | `File.addCommenter(email)` only |
| Change general access | `File.setSharing(access, permission)` |
| Protect a sheet or range | `Sheet.protect()` or `Range.protect()` |
| Transfer ownership | `File.setOwner(email)` |
Authorization and who the script runs as
The first time you run a script that touches sharing, Google asks you to authorize it. The script needs permission to see and manage your spreadsheets and Drive files. Read the consent screen before you approve it, because a script with these scopes can change access to your files.
Every change runs as a specific user. When you run a function from the editor or from a menu, it runs as you. Your own permissions therefore limit what the script can do:
- You can only change sharing on files where you are the owner or where sharing by editors is allowed. If the owner has restricted editors from changing permissions,
addEditorfails for you. - Organization policies still apply. If your administrator blocks sharing outside the domain, adding an outside address throws an error.
- Triggers run as the person who created them. Keep that in mind when a trigger changes protection later.
Sharing with specific people
This function grants Viewer and Editor access with SpreadsheetApp, and Commenter access through the matching Drive file, because Spreadsheet has no addCommenter method.
function shareWithPeople() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
ss.addViewer('[email protected]');
ss.addEditor('[email protected]');
// Spreadsheet has no addCommenter, so use the Drive file.
const file = DriveApp.getFileById(ss.getId());
file.addCommenter('[email protected]');
}Two behaviors are easy to miss.
First, these calls can send a notification email, just as the Share dialog does by default. Check the current behavior of the method you use. The Advanced Drive Service lets you control notifications when this matters.
Second, adding a role for someone who already has access changes their role. If a person is already an Editor and you call addViewer for them, check the result afterward rather than assuming they now have both. Use getViewers() and getEditors() to confirm the final state.
Sharing with a list
For more than a handful of people, keep addresses in an array or in a sheet range and loop over them. Reading from a sheet lets non-programmers maintain the list.
function shareFromList() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const file = DriveApp.getFileById(ss.getId());
const list = ss.getSheetByName('Access');
const rows = list.getRange('A2:B' + list.getLastRow()).getValues();
rows.forEach(function (row) {
const email = String(row[0]).trim();
const role = String(row[1]).trim().toLowerCase();
if (!email) return;
if (role === 'editor') {
file.addEditor(email);
} else if (role === 'commenter') {
file.addCommenter(email);
} else if (role === 'viewer') {
file.addViewer(email);
} else {
console.warn('Unknown role "' + role + '" for ' + email);
}
});
}This script expects a sheet named Access with emails in column A and the role in column B, starting at row 2. It skips blank rows and logs unknown roles instead of guessing. Validate the data before you run it, since a typo in an address can send access to the wrong person.
Setting general access
General access is the setting that decides whether anyone with the link can open the file. Scripts control it with File.setSharing(accessType, permissionType). This function sets general access to Anyone with the link with the Viewer role, which matches changing general access in the Share dialog.
function makeLinkViewOnly() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const file = DriveApp.getFileById(ss.getId());
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
}The access types you will use most are:
| Constant | Meaning |
|---|---|
| `DriveApp.Access.PRIVATE` | Restricted. Only people who were added can open the file. |
| `DriveApp.Access.ANYONE_WITH_LINK` | Anyone who has the link can open it. |
| `DriveApp.Access.DOMAIN_WITH_LINK` | Anyone in your Workspace domain who has the link. |
| `DriveApp.Access.ANYONE` | Anyone, with the file discoverable through search. |
Pair the access type with a permission such as VIEW, COMMENT or EDIT. Choose the lowest permission that does the job.
To lock a file back down, set it to private:
function makeRestricted() {
const file = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId());
file.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE);
}Calling setSharing does not remove people you added by name. They keep their roles. Restricting general access only closes the link route.
Protecting a sheet in code
A protection is an object attached to a sheet or range. It lists who may edit that area. The function below protects the active sheet so only the person running the script can edit it, even when other people have Editor access to the spreadsheet.
function protectActiveSheet() {
const sheet = SpreadsheetApp.getActiveSheet();
const protection = sheet.protect().setDescription('Totals - owner only');
const me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}The order of these steps matters:
sheet.protect()creates the protection. The description helps you find it later in Data > Protected sheets and ranges.addEditor(me)makes sure you are on the list. If you skipped this step and then removed everyone, you could lock yourself out of your own protection.removeEditors(protection.getEditors())clears the default editor list. The list now contains only you in effect, since the owner can always edit.setDomainEdit(false)stops everyone else in the domain from editing. ThecanDomainEdit()check avoids an error in accounts where the setting does not apply.
Protecting a range and leaving cells open
You can also protect a whole sheet except for some cells. This pattern is common for forms and templates where users fill in a few cells only.
function protectExceptInputs() {
const sheet = SpreadsheetApp.getActiveSheet();
const protection = sheet.protect().setDescription('Template - input cells open');
const open = [sheet.getRange('B2:B10'), sheet.getRange('D2:D10')];
protection.setUnprotectedRanges(open);
const me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors().filter(function (u) {
return u.getEmail() !== me.getEmail();
}));
}Here the filter keeps the current user in the list instead of removing and re-adding them. Either approach works. Pick the one that is easier to read for your team.
Another option is warning-only protection with protection.setWarningOnly(true). Editors can still change the area, but they see a warning first. This is a prompt, not a barrier, so do not rely on it for anything sensitive.
Finding and removing protections
Scripts can list protections, which helps when you audit or reset a sheet.
function listProtections() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const all = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE)
.concat(ss.getProtections(SpreadsheetApp.ProtectionType.SHEET));
all.forEach(function (p) {
const where = p.getRange().getA1Notation();
console.log(p.getDescription() + ' | ' + where + ' | editors: ' + p.getEditors().length);
});
}
function removeAllProtections() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getProtections(SpreadsheetApp.ProtectionType.RANGE).forEach(function (p) {
if (p.canEdit()) p.remove();
});
ss.getProtections(SpreadsheetApp.ProtectionType.SHEET).forEach(function (p) {
if (p.canEdit()) p.remove();
});
}canEdit() returns false when you are not allowed to change a protection, and calling remove() on it would throw. Checking first keeps the loop running.
Sharing a copy instead of the original
Scripts are not the only way to keep recipients away from your original. Replacing the trailing /edit in a spreadsheet URL with /copy prompts anyone who opens it to make their own copy, so they cannot change your original.
Original link: https://docs.google.com/spreadsheets/d/FILE_ID/edit
Copy link: https://docs.google.com/spreadsheets/d/FILE_ID/copyYou can build this link in a script from the file ID, then insert it in an email or a sheet cell:
function copyLink() {
const id = SpreadsheetApp.getActiveSpreadsheet().getId();
return 'https://docs.google.com/spreadsheets/d/' + id + '/copy';
}The person who opens the link still needs at least view access to the original.
Common errors and how to avoid them
- "You do not have permission to call..." The authorization step was skipped or a scope is missing. Run the function once from the editor and approve the prompt.
- Exceptions on
addEditororsetSharing. Your account may lack the right to share this file, or an organization policy blocks the target. Test the same change in the Share dialog to see the real reason. - Locking yourself out of a protection. Always add the intended editors before you remove the others.
- Assuming protection hides data. Protection stops edits. People with view access can still read protected cells.
- Looping over hundreds of addresses. Each call takes time and a script has execution limits. Process in batches and log progress.
- Hard-coded addresses in shared code. Keep lists in a sheet or in script properties so they are easy to review.
An audit function looks like this:
function auditSharing() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const file = DriveApp.getFileById(ss.getId());
console.log('Owner: ' + file.getOwner().getEmail());
console.log('General access: ' + file.getSharingAccess() + ' / ' + file.getSharingPermission());
console.log('Editors: ' + ss.getEditors().map(function (u) { return u.getEmail(); }).join(', '));
console.log('Viewers: ' + ss.getViewers().map(function (u) { return u.getEmail(); }).join(', '));
}Open View > Logs (or Executions) after the run to read the output.
A safe workflow
- Copy the spreadsheet and test the script on the copy.
- Run the audit function and save the output.
- Run the change function.
- Run the audit function again and compare.
- Confirm in the Share dialog that the result matches what you intended.
Exercise
A script calls file.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE). Afterward, a colleague you added earlier as Editor can still open the sheet. Is this a bug? Why or why not?
Show answer
No. setSharing changes only general access, the link route. People added by name keep their roles. To remove the colleague, call removeEditor(email) (or removeViewer/removeCommenter for other roles).
Exercise
You write sheet.protect() and then call protection.removeEditors(protection.getEditors()) without adding yourself first. What risk does this create, and how do you avoid it?
Show answer
You might remove your own edit rights on the protection and be unable to adjust it. Call protection.addEditor(Session.getEffectiveUser()) before removing the other editors, or filter yourself out of the list that you remove.
Exercise
Why does the Commenter role in the first example use DriveApp rather than SpreadsheetApp?
Show answer
Spreadsheet provides addViewer and addEditor but has no addCommenter method. The same role is available on the Drive File object, so the script gets the file with DriveApp.getFileById(ss.getId()) and calls addCommenter on it.