> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/appendix/gas/classes/protection.md).

# Protection

{% tabs %}
{% tab title="💈保護 range" %}

```javascript
// 1. get range A1:B10, 
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');

// 2. protect range
var protection = range.protect().setDescription('Sample protected range');

// 3. ensure current user is editor before removing. 
//    (Otherwise, if the user's edit permission comes from a group, 
//     the script throws an exception upon removing the group.)
var me = Session.getEffectiveUser();
protection.addEditor(me);

// 4. then remove all other users from the list of editors.
protection.removeEditors(protection.getEditors());

if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}
```

{% endtab %}

{% tab title="💈保護 sheet" %}

```javascript
// Protect the active sheet, then remove all other users (from edit)
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. 
// Otherwise, if the user's edit permission comes from a group, 
// the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());

if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

// --------------------------------------
//     protect sheet, unprotect range
// --------------------------------------

var protection = sheet.protect();
protection.setUnprotectedRanges([ranges]);
```

{% endtab %}

{% tab title="💈解除保護" %}

```javascript
// Remove all range protections in the spreadsheet 
// that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);

for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) { protection.remove() }
}
```

{% endtab %}

{% tab title="📘 手冊" %}

* GAS  ⟩ [Protection](https://developers.google.com/apps-script/reference/spreadsheet/protection) - protect / unprotect range / sheet.
  {% endtab %}

{% tab title="🗣 討論" %}

* [Protect ranges with google apps script](https://stackoverflow.com/a/39007278/5409815)
  {% endtab %}
  {% endtabs %}
