Sub topic 9
Creating protections with Apps Script
This chapter assumes you can protect ranges and sheets from the Google Sheets interface. It also assumes you know A1 notation and basic JavaScript (functions, const, arrow functions, arrays). You will write Apps Script functions that do the same work as the Data > Protect sheets and ranges dialog, and you will see where the script behaves differently from the interface.
Why script protections
The interface works well for one or two protections. It becomes slow and error-prone when you need the same protection on many sheets, when a template is copied every month, or when you want to check that protections are still in place. A script gives you three things:
- Repeatability. The same function produces the same protection every time.
- Reviewability. The protection rules sit in code that you can read and compare.
- Bulk work. One loop can protect a header row on every tab.
Apps Script is Google's JavaScript-based scripting platform. For Sheets, you can open it from Extensions > Apps Script. The function you write runs under the account of the person who runs it (or the account that owns a trigger), and that fact matters for protections, as you will see.
The objects involved
Three pieces make up the protection API in the SpreadsheetApp service:
| Piece | What it is | How you get it |
|---|---|---|
| `Range` | A block of cells, such as `A1:E1` | `sheet.getRange('A1:E1')` |
| `Sheet` | One tab of the spreadsheet | `SpreadsheetApp.getActiveSheet()` or `getSheetByName()` |
| `Protection` | The rule that locks a range or a sheet | `range.protect()` or `sheet.protect()` |
Calling protect() on a Range creates a range protection. Calling it on a Sheet creates a sheet protection. Both return a Protection object, and you configure that object with chained method calls. The protection exists as soon as protect() returns. The later calls only change its settings.
Protecting a range
The first example protects the header row A1:E1 and limits editing to the person running the script.
function protectHeaderRow() {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange('A1:E1');
const protection = range.protect().setDescription('Header row');
// Restrict editing to the user running the script (and the file owner).
protection.removeEditors(protection.getEditors());
protection.addEditor(Session.getEffectiveUser());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}Read it in order:
range.protect()creates the protection. By default, the protection editors list contains the user who created it, plus anyone who can already edit the protection by being the file owner.setDescription('Header row')gives the protection a label. Descriptions appear in the interface, and you will use them later to find protections again. Always set one.removeEditors(protection.getEditors())clears the editors list. The owner of the file always keeps access, so the owner is not truly removed.addEditor(Session.getEffectiveUser())adds the running user back explicitly. This makes the intent clear in the code.canDomainEdit()returnstrueonly for files owned by a Google Workspace account. If it istrue,setDomainEdit(false)stops everyone in the domain from editing the protected range. CallingsetDomainEditwhencanDomainEdit()isfalsethrows an error, so the check is required.
The editor list rules
Protection editors are people who can change the protected cells. They are different from spreadsheet editors. A person must already have edit access to the file before you can add them as a protection editor. If you call addEditor with an address that only has view access, or no access at all, the call does not give them anything useful. Treat the file's sharing settings and the protection's editor list as two separate gates, both of which must pass.
Other methods you will use often:
addEditors(emails)adds an array of email strings.removeEditor(emailOrUser)removes one person.getEditors()returns an array ofUserobjects.
Protecting a whole sheet with exceptions
A sheet protection locks every cell on the tab. You then name the cells that people may still change. The second example protects a budget tab but leaves B2:B20 open for input.
function protectSheetExceptInputs() {
const sheet = SpreadsheetApp.getActive().getSheetByName('Budget');
const protection = sheet.protect().setDescription('Budget sheet');
protection.setUnprotectedRanges([sheet.getRange('B2:B20')]);
}setUnprotectedRanges takes an array of Range objects, even when you pass only one. The unprotected ranges stay editable by anyone who already has edit access to the spreadsheet. This example does not touch the editors list, so the sheet itself is locked to the default editors only. Everyone else with file edit access can type into B2:B20, and nowhere else.
Two details to remember:
setUnprotectedRangesreplaces the previous list. To add a range later, read the current list withgetUnprotectedRanges(), append to it, and set it again.- The unprotected ranges must be on the same sheet as the protection. A range from another tab is not valid.
Choosing between range and sheet protection
| Situation | Better choice |
|---|---|
| A few cells or one column need locking | Range protection |
| Most of the tab should be locked, with a few input cells | Sheet protection with unprotected ranges |
| Inputs may move or grow | Range protection on the stable parts, since a long unprotected list is hard to maintain |
Warning-only protection
A warning-only protection does not block anyone. When a person edits the range, Sheets shows a confirmation prompt, and they can accept it and continue.
function warnOnEdit() {
const range = SpreadsheetApp.getActiveSheet().getRange('D2:D100');
range.protect()
.setDescription('Calculated column')
.setWarningOnly(true);
}Use this for cells that hold formulas or derived values, where an accidental overwrite is the realistic risk and a determined edit is acceptable. Warning-only protections have no editors list. If you call setWarningOnly(true), the editor settings no longer apply, and addEditor or removeEditors calls made after it do not change who can edit.
How a script decides what happens
The sequence below shows what happens when a script protects a range and restricts its editors.
Listing protections
To audit a file, you need to see what exists. sheet.getProtections(type) returns an array of Protection objects of one type. The type is a value of SpreadsheetApp.ProtectionType, which is either RANGE or SHEET.
function listProtections() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getSheets().forEach(sheet => {
const rangeProtections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
const sheetProtections = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
rangeProtections.concat(sheetProtections).forEach(p => {
Logger.log('%s | %s | %s | warningOnly=%s',
sheet.getName(),
p.getRange().getA1Notation(),
p.getDescription(),
p.isWarningOnly());
});
});
}The log shows one line per protection. For a sheet protection, getRange() returns the whole sheet's range, so the A1 notation covers the full grid. To see the exceptions for a sheet protection, call getUnprotectedRanges() and log each range's A1 notation.
Run the function, then open View > Logs (or Execution log) to read the output. A log line looks like this:
Budget | A1:Z1000 | Budget sheet | warningOnly=falseDescriptions are optional, so getDescription() may return an empty string for protections someone created through the interface without a label. An audit that prints blank descriptions is itself a finding.
Removing protections
Removal is a call to remove() on the Protection object. Before you call it, check canEdit(), which returns whether the current user may change that protection. If the user cannot edit it, remove() throws an error and stops your loop.
function removeProtectionsByDescription(description) {
const sheet = SpreadsheetApp.getActiveSheet();
sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE).forEach(p => {
if (p.getDescription() === description && p.canEdit()) {
p.remove();
}
});
}A function that takes a parameter cannot be run directly from the editor's Run button, because the button passes no arguments. Call it from a wrapper:
function removeHeaderProtections() {
removeProtectionsByDescription('Header row');
}This function deletes only range protections on the active sheet. To clean a whole file, loop over getSheets() as in the audit function. To remove a sheet protection, request ProtectionType.SHEET instead.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Exception on `setDomainEdit` | The file is not owned by a Workspace account | Guard the call with `canDomainEdit()` |
| Exception on `remove()` | The running user is not allowed to edit that protection | Guard with `canEdit()` |
| Editors list does not match expectations | The file owner always keeps access, and users without file edit access cannot be useful editors | Check sharing settings before blaming the script |
| Protection created twice | The script ran more than once and each run added a new protection | Remove old protections by description first, then create |
| `getActiveSheet()` returns the wrong tab | The script was run from a trigger or a different active tab | Use `getSheetByName()` for scripts that run unattended |
| Calling `protect()` on a range already covered | Overlapping protections stack, and a user must pass all of them | Audit before adding |
Duplicates are the most common problem. A script that creates protections should be idempotent, meaning that running it twice leaves the same result as running it once. The simplest way is to delete matching protections first.
function ensureHeaderProtection() {
const sheet = SpreadsheetApp.getActiveSheet();
removeProtectionsByDescription('Header row');
const protection = sheet.getRange('A1:E1').protect().setDescription('Header row');
protection.removeEditors(protection.getEditors());
protection.addEditor(Session.getEffectiveUser());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}This works because removeProtectionsByDescription is defined in the same project. Apps Script files share one global scope.
Authorization and who runs the script
The first run asks you to authorize the script. The script needs access to the spreadsheet, and this covers protection changes. When the script runs, the "effective user" is the person who started it, or the person who installed a trigger. This has two results:
- A protection created by a collaborator is editable by that collaborator, even if you intended it to be yours alone. Your script should set the editors list explicitly rather than rely on the default.
- A time-driven trigger runs as the person who created it. If that person loses access to the file, the trigger fails.
Exercises
Exercise
A script calls sheet.protect() and then setUnprotectedRanges([sheet.getRange('B2:B20')]). A teammate who has edit access to the file, but is not a protection editor, tries to type in C5 and in B5. What happens in each case?
Show answer
The edit in C5 is blocked, because the sheet is protected and C5 is not an exception. The edit in B5 is allowed, because B5 is in the unprotected range and the teammate already has edit access to the spreadsheet.
Exercise
You run ensureHeaderProtection three times. Why does the sheet end up with one header protection, and what would happen if the first line of the function, removeProtectionsByDescription('Header row'), were deleted?
Show answer
Each run first deletes any range protection whose description is "Header row", then creates a new one, so only one remains. Without that line, each run would add another protection on A1:E1, leaving three overlapping protections.
Exercise
Write the guard that prevents an exception when you try to restrict domain editing on a protection.
Show answer
Check canDomainEdit() before calling setDomainEdit(false):
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
canDomainEdit() is true only when the file is owned by a Google Workspace account.